就是在创建对象时,不是通过直接New来创建实例,而是通过一个工厂类来创建实例,给他传不同的标识他就返回给我什么样的对象。
优点:帮助封装,不用操心具体的对象实现过程;实现了客户端和具体实现类的解耦。
缺点:可能增加客户端的复杂度;
什么时候使用工厂模式:想要把对外创建对象的职责集中管理和控制时。
Code:
接口:Interface1
public interface Interface1 {
public void say();
}
实现类:Son1
public class Son1 implements Interface1{
@Override
public void say() {
System.out.println("Son1");
}
}
实现类:Son2
public class Son2 implements Interface1 {
@Override
public void say() {
System.out.println("Son2");
}
}
public class Interface1Factory {
public static Interface1 create(int i){
Interface1 i1;
if(i == 1)
i1 = new Son1();
else
i1 = new Son2();
return i1;
}
}
测试类:Test
public class Test {
public static void main(String args[]){
Interface1 i1 = Interface1Factory.create(1);
i1.say();
}
}