设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
老蒋每日coding6 小时前
AI智能体设计模式系列(一)—— 提示词链
设计模式·ai编程
sxlishaobin10 小时前
设计模式之模板方法模式
设计模式·模板方法模式
le16161610 小时前
设计模式之单例模式
单例模式·设计模式
Knight_AL10 小时前
从单例模式说起:Java 常见设计模式的理解与实践
java·单例模式·设计模式
Engineer邓祥浩10 小时前
设计模式学习(10) 23-8 装饰者模式
python·学习·设计模式
老蒋每日coding11 小时前
基于LangGraph的AI Agent并行化设计模式详解
设计模式·ai编程
GISer_Jing11 小时前
AI学习资源总结:免费开放,入门至深入,持续更新
人工智能·学习·设计模式·prompt·aigc
Geoking.12 小时前
【设计模式】策略模式(Strategy)详解:把 if-else 变成可切换的算法
java·设计模式·策略模式
老蒋每日coding12 小时前
AI智能体设计模式系列(二)—— 路由模式
人工智能·设计模式
老蒋每日coding12 小时前
AI智能体设计模式系列(四)—— 反思模式
设计模式