设计模式之工厂模式

工厂模式

工厂模式(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.屏蔽产品的具体实现,调用者只关心产品的接口。

缺点:

每增加一个产品时,都要增加相对应的对象和工厂,如果增加的多了,所对应的系统的复杂度也会增加。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值