设计模式-抽象工厂模式

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

手机产品

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();
    }
}

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

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

相关推荐
日和雫17 小时前
面向对象与面向过程,谁才是“银弹”?
设计模式
geovindu1 天前
rust: Iterator Pattern
开发语言·后端·设计模式·rust·行为模式·迭代器模
高晶2 天前
ARM 嵌入式 Linux 系统启动流程实战指南
设计模式·程序员
高晶2 天前
BMS 通信开发实战:从 PMBus 协议到数据采集的完整指南
设计模式·程序员
geovindu2 天前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模
电子IT笔记2 天前
老MES登录改造:弱密码和暴破一起治
设计模式
牧瀬クリスだ2 天前
单例模式终极指南:从入门到防破坏
单例模式·设计模式
博风2 天前
9、设计模式应用举例:责任链模式:计算阶乘
设计模式·责任链模式
电子IT笔记2 天前
人走了,记录不能“空白”: MES×HR 离职人员下拉回显实战
设计模式
博风3 天前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式