设计模式-抽象工厂模式

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

手机产品

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

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

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

相关推荐
石一峰69911 小时前
C 语言函数设计模式实战经验
c语言·开发语言·设计模式
qq_2975746712 小时前
设计模式系列文章(基础篇第22篇):访问者模式——分离数据结构与操作,实现灵活扩展
数据结构·设计模式·访问者模式
刀法如飞20 小时前
领域驱动 vs 本体驱动:DDD 代码建模与 Ontology 语义建模的对比分析
设计模式·架构设计·领域驱动
我爱cope1 天前
【Agent智能体26 | 多智能体-多智能体工作流】
人工智能·设计模式·语言模型·职场和发展
咖啡八杯2 天前
【无标题】
java·后端·设计模式
折哥的程序人生 · 物流技术专研2 天前
Java 23 种设计模式:从踩坑到精通 | 适配器模式 —— 让不兼容的接口也能一起工作
java·设计模式·面试·适配器模式·单一职责原则
布朗克1682 天前
33 设计模式精讲
java·单例模式·设计模式
geovindu2 天前
python: Generators Pattern
开发语言·python·设计模式·生成器模式
雨浓YN2 天前
基于设计模式的Winform软件框架-01Xml\Log\Ini日志(单例模式+生产者消费者模式)
单例模式·设计模式