设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
工一木子5 分钟前
设计模式与生活⑩:地铁没变,你换了个状态
设计模式
是2的10次方啊2 小时前
设计模式与生活⑪:地铁里被打扰,别总靠自己硬扛
设计模式
高晶16 小时前
SPMI 控制器 RTL 设计与验证新手入门
设计模式·程序员·架构
geovindu1 天前
rust:N-Barrier Pattern
开发语言·后端·设计模式·rust·屏障模式·并发型模式
顧棟1 天前
OpenAPI 网关:鉴权 + 流量治理 一体化设计方案与实现
java·spring boot·设计模式
拆房老料1 天前
【第四部分:Agentic 智能体设计模式】17. Agent 路由模式详解:从意图识别到动态模型选择
java·设计模式·ai编程·策略模式
是2的10次方啊1 天前
设计模式与生活⑩:地铁没变,你换了个状态
设计模式
步行cgn2 天前
适配器设计模式:一个“翻译官”的故事
设计模式
扶尔魔ocy2 天前
【QT C++】常用设计模式
c++·设计模式
她说..2 天前
常见设计模式-观察者模式
java·spring boot·spring·观察者模式·设计模式