设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
vivo互联网技术3 小时前
软件不是从数据开始,而是从现实开始 | KDC 系列 01
设计模式·架构·领域驱动设计
码匠许师傅3 小时前
【设计模式精讲】27.模板方法模式(Template Method)
c++·设计模式·uml·模板方法模式
码匠许师傅6 小时前
【设计模式精讲】28.访问者模式(Visitor)
java·设计模式·访问者模式
码匠许师傅1 天前
【设计模式精讲】26.策略模式(Strategy)
c++·设计模式·策略模式·uml
Ysx1 天前
AI 问答不再"一本正经地胡说":30 轮提示词迭代,沉淀 4 条防幻觉铁律
设计模式
码匠许师傅1 天前
【设计模式精讲】25.状态模式(State)
c++·ui·设计模式·状态模式·uml
geovindu1 天前
java:Observer Pattern
java·开发语言·后端·观察者模式·设计模式·行为模式
码匠许师傅2 天前
【设计模式精讲】24.观察者模式(Observer)
c++·观察者模式·设计模式·uml
小程故事多_802 天前
从快速迭代到稳定存续,Google五大设计模式重构长效AI智能体落地逻辑
人工智能·设计模式·重构
码匠许师傅3 天前
【设计模式精讲】22.中介者模式(Mediator)
c++·设计模式·软件工程·uml·中介者模式