设计模式-工厂模式

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

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 小时前
GoF 23 种设计模式完整知识总结与使用教程
java·c语言·开发语言·python·设计模式
UrSpecial5 小时前
设计模式:模板方法模式
设计模式·模板方法模式
如来神掌十八式7 小时前
设计模式之装饰器模式
java·设计模式
qqxhb20 小时前
26|Agent 设计模式:ReAct、Plan-and-Solve 与反射
设计模式·react模式·plan-and-solve·reflection模式
hssfscv21 小时前
软件设计师下午题六——Java的各种设计模式
java·算法·设计模式
zhaoshuzhaoshu1 天前
设计模式之创建型设计模式详细解析(含示例)
单例模式·设计模式·架构
倚楼盼风雨1 天前
浅析设计模式-23种设计模式剖析
设计模式
Momentary_SixthSense2 天前
设计模式之工厂模式
java·开发语言·设计模式
Java码农也是农2 天前
Multi-Agent 系统设计模式
设计模式·agent·multi-agent
sg_knight2 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state