设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
博风42 分钟前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式
高晶2 小时前
ARM 嵌入式 Linux 系统 U-Boot 开发与移植实战M
设计模式·程序员
geovindu7 小时前
rust: Chain of Responsibility Pattern
开发语言·后端·设计模式·rust·责任链模式·行为模式
拆房老料8 小时前
【第四部分:Agentic 智能体设计模式】15.为什么 Agent 也需要设计模式
人工智能·设计模式·ai·ai-native
geovindu9 小时前
rust: Chain of Responsibility Pattern (续)
开发语言·后端·设计模式·rust·责任链模式·行为模式
Lost of 程序猿9 小时前
责任链模式实战:审批流里“层层把关“的艺术
后端·设计模式·asp.net·责任链模式
希洛兔1 天前
状态模式详解:让对象随内部状态自动改变行为
java·设计模式·状态模式
博风1 天前
7、设计模式应用举例:策略模式:加密、解密文件
设计模式·策略模式
4SAPI1 天前
Provider Adapter设计模式:如何让AI应用支持多个模型
网络·人工智能·设计模式
geovindu1 天前
rust: pool Pattern
开发语言·后端·设计模式·rust·对象池简写模式