interface Fruit {
public abstract void eat();
}
class Apple implements Fruit {
public void eat() {
System.out.println("吃苹果");
}
}
class Orange implements Fruit {
public void eat() {
System.out.println("吃橙子");
}
}
//设计一个中间工厂类
//客户端只取得父类接口下的子类对象
//程序的改变不影响客户端的使用
//客户端不必关注细节
class Factory {
public static Fruit getInstance(String className) {
if ("Apple".equals(className)) {
return new Apple();
} else if ("Orange".equals(className)) {
return new Orange();
} else {
return null;
}
}
}
public class TestDemo {
public static void main(String[] args) {
Fruit f = Factory.getInstance("Orange");
f.eat();
}
}
接口的应用工厂设计模式(Factory)
最新推荐文章于 2025-04-20 16:29:39 发布