设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
Kel12 小时前
Node.js 单线程高并发:从内核中断到 JS 回调的完整技术栈
设计模式·架构·node.js
解局易否结局1 天前
ArkUI MVI 架构实战:单向数据流设计模式在 HarmonyOS NEXT 中的深度实践
华为·设计模式·架构·harmonyos
解局易否结局2 天前
ArkTS 设计模式与架构进阶:构建可维护的 HarmonyOS 应用
华为·设计模式·架构·harmonyos
happyness442 天前
AI编程与设计模式
设计模式·ai编程
就是小王同学啊2 天前
Spring小技巧之设计模式
sql·spring·设计模式
Larcher2 天前
当 AI 学会写代码:一个自动生成 React 项目的 Agent 实战
人工智能·设计模式·程序员
zjun10013 天前
C++常用的设计模式
c++·设计模式
我登哥MVP3 天前
走进 Gang of Four 设计模式:解释器模式
java·设计模式·解释器模式
我登哥MVP3 天前
走进 Gang of Four 设计模式:过滤器模式
java·设计模式·过滤器模式
kisshyshy3 天前
从无崖子到OpenAI:大模型间的“传功”,动了谁的奶酪?
人工智能·深度学习·设计模式