设计模式-抽象工厂模式

抽象工厂模式:该模式是对工厂模式的拓展,因为工厂模式中创建的产品都需要继承自同一个父类或接口,创建的产品类型相同,无法创建其他类型产品,所以抽象工厂模式对其进行拓展,使其可以创建其他类型的产品。

手机产品

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface Phone
{
    void Name();
}

public class IPhone : Phone
{
    public void Name()
    {
        Debug.Log("苹果手机");
    }
}

public class AZPhone : Phone
{
    public void Name()
    {
        Debug.Log("安卓手机");
    }
}

Pad产品

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface Pad
{
    void Name();
}


public class IPad : Pad
{
    public void Name()
    {
        Debug.Log("苹果Pad");
    }
}

public class AZPad : Pad
{
    public void Name()
    {
        Debug.Log("安卓Pad");
    }
}

工厂

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface IFactory
{
    Phone Creat();
    Pad creatPad();
}

public class IPhoneFactory : IFactory
{
    public Phone Creat()
    {
        return new IPhone();
    }

    public Pad creatPad()
    {
        return new IPad();
    }
}

public class AZPhoneFactory : IFactory
{
    public Phone Creat()
    {
        return new AZPhone();
    }

    public Pad creatPad()
    {
        return new AZPad();
    }
}

优点:创建的产品种类不单一

缺点:当新增一大类产品时需要修改工厂脚本,违反开闭原则

相关推荐
装不满的克莱因瓶2 小时前
设计模式之策略模式核心概念和应用场景
java·后端·设计模式·架构·系统架构·策略模式
是2的10次方啊16 小时前
设计模式与生活㉑:一句“建议复查”,是好几句话拼出来的
设计模式
杯子不吃紫菜2 天前
LangGraph 体系实战(下):中断恢复、流式、子图与设计模式
单片机·嵌入式硬件·设计模式
是2的10次方啊2 天前
设计模式与生活⑳:楼里的事都找前台,你就再没见过师傅
设计模式
是2的10次方啊3 天前
设计模式与生活⑲:投影连不上,别急着换投影仪
设计模式
cjz38994 天前
规则树:把一百行if-else拆成一棵树
设计模式
Adellle4 天前
设计模式指南 (Java 版) ㊁
java·开发语言·设计模式
是2的10次方啊4 天前
设计模式与生活⑱:工资还没焐热,账单已经凑成一摞
设计模式
百思不得小李5 天前
一个复杂的动态表单是如何实现的
前端·设计模式
爱你真是太好了5 天前
上下文组成以及如何压缩
设计模式