接口的应用(二)—— 工厂设计模式(Factory)
首先,如果想确认一个代码是否真的好,有这么几个标准:
- 客户端调用简单,不需要关注具体的实现细节;
- 客户端之外的代码修改,不影响用户的使用,即:用户可以 不去关心代码是否变更。
eg.
public interface IFruit {
public void eat();
}
public class Orange implements IFruit {
public void eat() {
System.out.println("吃橘子~");
}
}
public class Apple implements IFruit {
public void eat() {
System.out.println("吃苹果~");
}
}
public class Test {
public static void main(String[] args) {
IFruit fruit = new Apple(); //每次改变水果类型,客户端代码都要修改,这样使得代码的耦合度太高
fruit.eat();
}
}
修改:
public interface IFruit {
public void eat();
}
public class Orange implements IFruit {
public void eat() {
System.out.println("吃橘子~");
}
}
public class Apple implements IFruit {
public void eat() {
System.out.println("吃苹果~");
}
}
//定义一个工厂类,用于获得水果类的实例
public class Factory {
public static IFruit getInstance(String className) {
if ("apple".equals(className)) {
return new Apple();
}else if ("orange".equals(className)) {
return new Orange();
}else
return null;
}
}
//现在客户端不会看见具体的子类,因为所有的接口对象都是通过Factory类取得的,
//如果日后需要扩充新的IFruit子类对象,则只需要修改Factory类即可,但客户端的调用不会发生变化。
public class Test {
public static void main(String[] args) {
Factory f =new Factory();
IFruit fruit = f.getInstance("apple");
fruit.eat();
}
}
运行结果:
吃苹果~
- 工厂模式结构图: