设计模式-工厂模式

工厂模式:该模式是将简单工厂模式中的工厂作为一个基类(接口),当需要创建的产品(具体子类实例)增加时,不修改原工厂的创建方法,而是增加一个具体工厂子类,由该子类去创建新增的产品,将产品子类的实例化延迟到工厂子类中。

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("安卓手机");
    }
}

这是工厂的实现

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

public interface IFactory
{
    Phone Creat();
}

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

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

优点:降低了耦合性,只需要知道要什么产品,不用管创建过程;

更易于扩展;

缺点:代码复杂度提高

相关推荐
raindayinrain1 天前
c++设计模式
开发语言·c++·设计模式
工一木子1 天前
设计模式与生活⑦:你打的车,隔着一个平台
设计模式
电子科技圈1 天前
2026 RISC-V中国峰会观察:编译调试工具链的“在场节奏”,释放了什么信号?
大数据·人工智能·设计模式·软件工程·软件构建·代码规范·risc-v
电子科技圈1 天前
Arm电机控制开发工具哪家强?
arm开发·单片机·嵌入式硬件·设计模式·软件构建
是2的10次方啊2 天前
设计模式与生活⑦:你打的车,隔着一个平台
设计模式
geovindu2 天前
rust: Read-Write Lock Pattern
开发语言·后端·设计模式·rust·读写锁模式·同步型模式
工一木子3 天前
设计模式与生活⑤:天冷了,给电动车套件挡风被
设计模式
是2的10次方啊3 天前
设计模式与生活⑥:问题一个个砸过来,先写张便签
设计模式
是2的10次方啊4 天前
设计模式与生活⑤:天冷了,给电动车套件挡风被
设计模式
昭昭日月明5 天前
AI 时代的《重构》
设计模式·架构