验证中...
工厂模式
Raw Copy
public class ClassDemo {
public static void main(String[] args) {
Fruit fruit = Factory.getInstance("cn.wyp.reflect.Apple",Fruit.class);
fruit.eat();
}
}
class Factory{
private Factory(){}
//cls参数仅用于标识是那个接口的子类
public static <T> T getInstance(String className,Class<T> cls){
T c = null;
try {
//注:此时的缺点:只能调用无参构造
c = (T)Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
}
interface Drink{
public void drink();
}
class Tea implements Drink{
@Override
public void drink() {
System.out.println("喝茶");
}
}
class Cola implements Drink{
@Override
public void drink() {
System.out.println("喝可乐");
}
}
interface Fruit{
public void eat();
}
class Apple implements Fruit{
@Override
public void eat() {
System.out.println("吃苹果");
}
}
class Orange implements Fruit{
@Override
public void eat() {
System.out.println("吃橘子");
}
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search

183227_9af5e6a8_1826025 111910_4d91f001_1826025