设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
解局易否结局10 小时前
ArkUI MVI 架构实战:单向数据流设计模式在 HarmonyOS NEXT 中的深度实践
华为·设计模式·架构·harmonyos
解局易否结局12 小时前
ArkTS 设计模式与架构进阶:构建可维护的 HarmonyOS 应用
华为·设计模式·架构·harmonyos
happyness4412 小时前
AI编程与设计模式
设计模式·ai编程
就是小王同学啊13 小时前
Spring小技巧之设计模式
sql·spring·设计模式
Larcher1 天前
当 AI 学会写代码:一个自动生成 React 项目的 Agent 实战
人工智能·设计模式·程序员
我登哥MVP2 天前
走进 Gang of Four 设计模式:解释器模式
java·设计模式·解释器模式
我登哥MVP2 天前
走进 Gang of Four 设计模式:过滤器模式
java·设计模式·过滤器模式
kisshyshy2 天前
从无崖子到OpenAI:大模型间的“传功”,动了谁的奶酪?
人工智能·深度学习·设计模式
某不知名網友3 天前
C++ 六大常用设计模式详解(单例、工厂、策略、状态、观察者、代理)
开发语言·c++·设计模式
咖啡八杯3 天前
GoF设计模式——责任链模式
设计模式·面试·架构