设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
Larcher6 小时前
当 AI 学会写代码:一个自动生成 React 项目的 Agent 实战
人工智能·设计模式·程序员
我登哥MVP13 小时前
走进 Gang of Four 设计模式:解释器模式
java·设计模式·解释器模式
我登哥MVP14 小时前
走进 Gang of Four 设计模式:过滤器模式
java·设计模式·过滤器模式
kisshyshy1 天前
从无崖子到OpenAI:大模型间的“传功”,动了谁的奶酪?
人工智能·深度学习·设计模式
某不知名網友2 天前
C++ 六大常用设计模式详解(单例、工厂、策略、状态、观察者、代理)
开发语言·c++·设计模式
咖啡八杯2 天前
GoF设计模式——责任链模式
设计模式·面试·架构
大辉狼_音频架构2 天前
Vol.01 高频设计模式
设计模式
我登哥MVP3 天前
走进 Gang of Four 设计模式:代理模式
设计模式·代理模式
我登哥MVP3 天前
走进 Gang of Four 设计模式:外观模式
java·设计模式·外观模式
ttod_qzstudio3 天前
【软考设计模式】备忘录模式:对象状态的捕获与无损恢复精讲
设计模式·备忘录模式