设计模式-抽象工厂模式

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

手机产品

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

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

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

相关推荐
咖啡八杯6 小时前
GoF设计模式——迭代器模式
java·后端·设计模式·迭代器模式
ttod_qzstudio8 小时前
【软考设计模式】外观模式:复杂子系统的“门面“封装与代码填空精讲
设计模式·外观模式
geovindu14 小时前
CSharp: Prototype Pattern
开发语言·后端·设计模式·.net·原型模式·创建型模式
ttod_qzstudio15 小时前
【软考设计模式】组合模式:“部分-整体“层次结构与树形对象统一操作精讲
设计模式·组合模式
ttod_qzstudio17 小时前
【软考设计模式】装饰模式:“套娃“式增强与动态职责扩展精讲
设计模式·装饰模式
烬羽18 小时前
MCP 多服务器架构实战:一个 Agent 同时操控地图、浏览器和文件
设计模式·设计
阿pin20 小时前
Android随笔-常用的设计模式
android·设计模式
儒雅的名21 小时前
GoF设计模式——策略模式
设计模式·bash·策略模式
折哥的程序人生 · 物流技术专研1 天前
第4篇:Lambda 简化策略模式(Java 8+)
java·设计模式·策略模式·函数式编程·lambda·代码简化·扩充系列
jsonbro2 天前
手把手带你实现发布订阅模式
前端·vue.js·设计模式