03 抽象工厂

抽象工厂模式

抽象工厂, 工厂的根源在一个顶层接口 GeneralFactory 通过实现顶层接口来创建具体的产品生产工厂。 GeneralFactory 只依赖产品的抽象层, 具体的产品选择由具体的生产工厂决定。抽象工厂

demo

package creationalpattern.factorypattern;

/**
 * @author tx
 * @version 1.0
 * @date 2024/1/5 22:20
 * @description:
 * 抽象工厂,
 * 工厂的根源在一个顶层接口 GeneralFactory
 * 通过实现顶层接口来创建具体的产品生产工厂。
 * GeneralFactory 只依赖产品的抽象层,
 * 具体的产品选择由具体的生产工厂决定。
 */
public class AbstractFactoryPattern {
    public static void main(String[] args) {
        // 创建A工厂
        GeneralFactory aFactory = new AFactory();
        // 通过工厂拿货
        AAProduct aaProduct = aFactory.createAAProduct();
        ABProduct abProduct = aFactory.createABProduct();
        aaProduct.run();
        abProduct.go();
        // 创建B工厂
        GeneralFactory bFactory = new BFactory();
        // 通过工厂拿货
        AAProduct aaProduct1 = bFactory.createAAProduct();
        ABProduct abProduct1 = bFactory.createABProduct();
        aaProduct1.run();
        abProduct1.go();
    }
}

/**
 * 抽象产品A
 */
interface AAProduct{
    /**
     * 产品应该具备的功能
     */
    void run();
}
class AAAProductImpl implements AAProduct{

    /**
     * 产品应该具备的功能
     */
    @Override
    public void run() {
        System.out.println("产品A的A款");
    }
}
class AABProductImpl implements AAProduct{

    /**
     * 产品应该具备的功能
     */
    @Override
    public void run() {
        System.out.println("产品A的B款");
    }
}
/**
 * 抽象产品B
 */
interface ABProduct{
    /**
     * 产品应该具备的功能
     */
    void go();
}
class ABAProductImpl implements ABProduct{

    /**
     * 产品应该具备的功能
     */
    @Override
    public void go() {
        System.out.println("产品B的A款");
    }
}
class ABBProductImpl implements ABProduct{

    /**
     * 产品应该具备的功能
     */
    @Override
    public void go() {
        System.out.println("产品B的B款");
    }
}
/**
 * 抽象总工厂
 */
interface GeneralFactory{
    AAProduct createAAProduct();
    ABProduct createABProduct();
}

/**
 * 生产产品 A 的 A 款,B 的 A 款
 */
class AFactory implements GeneralFactory{

    /**
     * @return A-A
     */
    @Override
    public AAProduct createAAProduct() {
        return new AAAProductImpl();
    }

    /**
     * @return B-A
     */
    @Override
    public ABProduct createABProduct() {
        return new ABAProductImpl();
    }
}
/**
 * 生产产品 A 的 B 款,B 的 B 款
 */
class BFactory implements GeneralFactory{

    /**
     * @return A-B
     */
    @Override
    public AAProduct createAAProduct() {
        return new AABProductImpl();
    }

    /**
     * @return B-B
     */
    @Override
    public ABProduct createABProduct() {
        return new ABBProductImpl();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值