设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
在未来等你32 分钟前
AI Agent设计模式 Day 19:Feedback-Loop模式:反馈循环与自我优化
设计模式·llm·react·ai agent·plan-and-execute
兵bing5 小时前
设计模式-访问者模式
设计模式·访问者模式
python零基础入门小白5 小时前
【万字长文】大模型应用开发:意图路由与查询重写设计模式(从入门到精通)
java·开发语言·设计模式·语言模型·架构·大模型应用开发·大模型学习
MC丶科6 小时前
Java设计模式漫画英雄宇宙-工厂模式 —Factory博士的“超级英雄制造机”!
java·设计模式·漫画
明洞日记7 小时前
【设计模式手册013】命令模式 - 请求封装的优雅之道
java·设计模式·命令模式
ada0_ada17 小时前
行为型模式:②命令模式(Command Pattern)
设计模式
o0向阳而生0o8 小时前
113、23种设计模式之中介者模式(21/23)
设计模式·中介者模式
心语星光8 小时前
23种经典设计模式
设计模式
ACE19851 天前
AI Agent 设计模式深度解析:提示链(Prompt Chaining)模式
人工智能·设计模式·prompt
明洞日记1 天前
【设计模式手册012】责任链模式 - 请求处理的流水线艺术
java·设计模式·责任链模式