设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
sinat_2554878113 小时前
IDEA:查找文件/类
java·ide·设计模式·intellij-idea
cg.family15 小时前
Java设计模式的七大原则
java·设计模式
deephub16 小时前
Agentic 设计模式拆解:6 种结构的优缺点与应用场景
人工智能·设计模式·大语言模型·多智能体
雪度娃娃17 小时前
行为型设计模式——访问者模式
设计模式·访问者模式
老码观察20 小时前
设计模式实战解读(四):观察者模式——事件驱动的解耦利器
观察者模式·设计模式·log4j
我爱cope21 小时前
【Agent智能体7 | 智能体设计模式】
人工智能·设计模式
詩飛21 小时前
设计模式之建造者模式&模版模式、策略模式
后端·设计模式
IT空门:门主1 天前
Java 设计模式实战:模板方法 + 工厂 + 策略模式重构支付系统
java·设计模式·策略模式
geovindu1 天前
go: N-Barrier Pattern
开发语言·后端·设计模式·golang·屏障模式