设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
羞儿5 小时前
Agent设计模式与工程化
设计模式·知识图谱·agent·rag·mcp·指导开发
点云SLAM7 小时前
C++(C++17/20)最佳工厂写法和SLAM应用综合示例
开发语言·c++·设计模式·c++实战·注册工厂模式·c++大工程系统
Yu_Lijing10 小时前
基于C++的《Head First设计模式》笔记——状态模式
c++·笔记·设计模式
Engineer邓祥浩11 小时前
设计模式学习(18) 23-16 迭代器模式
学习·设计模式·迭代器模式
老蒋每日coding13 小时前
AI Agent 设计模式系列(十三)—— 人机协同模式
人工智能·设计模式·langchain
老蒋每日coding14 小时前
AI Agent 设计模式系列(十二)—— 异常处理和恢复模式
人工智能·设计模式
小码过河.14 小时前
设计模式——抽象工厂模式
设计模式·抽象工厂模式
国强_dev1 天前
量体裁衣在技术方案中的应用
设计模式·系统架构
Engineer邓祥浩1 天前
设计模式学习(16) 23-14 命令模式
学习·设计模式·命令模式
Maddie_Mo1 天前
智能体设计模式 第二章:路由模式
设计模式