工厂模式
工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
实现过程
1. 创建一个家庭(Family)接口
public interface Family {
void show();
}
2. 创建实现接口的实体类
- 父亲类(Father)
public class Father implements Family{
@Override
public void show() {
System.out.println("This is Father");
}
}
- 母亲类(Mother)
public class Mother implements Family {
@Override
public void show() {
System.out.println("This is Mother");
}
}
- 儿子类(Son)
public class Son implements Family {
@Override
public void show() {
System.out.println("This is Son");
}
}
3. 创建一个工厂(FamilyFactory)并生成对应实体类的对象
public class FamilyFactory {
//使用get方法获取对象
public Family getFamily(String familyType){
if (familyType == null){
return null;
}
if (familyType.equalsIgnoreCase("Dad")){
return new Father();
}
else if (familyType.equalsIgnoreCase("Mom")) {
return new Mother();
}
else if (familyType.equalsIgnoreCase("Baby")){
return new Son();
}
return null;
}
}
4. 创建测试类(FactoryPatternTest),使用该工厂
public class FactoryPatternTest {
public static void main(String[] args) {
FamilyFactory familyFactory = new FamilyFactory();
Family family1 = familyFactory.getFamily("Baby");
family1.show();
Family family2 = familyFactory.getFamily("Dad");
family2.show();
Family family3 = familyFactory.getFamily("Mom");
family3.show();
}
}
5. 输出结果
This is Son
This is Father
This is Mother
优点:
1.扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以了。
2.屏蔽产品的具体实现,调用者只关心产品的接口。
缺点:
每增加一个产品时,都要增加相对应的对象和工厂,如果增加的多了,所对应的系统的复杂度也会增加。