设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
guangzan6 小时前
常用设计模式:模板方法模式
设计模式
Lei_3359679 小时前
[設計模式]二十三種設計模式
设计模式
吃饺子不吃馅10 小时前
面试官:JWT、Cookie、Session、Token有什么区别?
前端·设计模式·面试
leafff12312 小时前
一文读懂:如何选择适合的RAG系统架构设计模式?
设计模式·自然语言处理·系统架构
ZHE|张恒14 小时前
设计模式实战篇(一):彻底搞懂 Singleton 单例模式
单例模式·设计模式
喝拿铁写前端1 天前
从面条代码到抽象能力:一个小表单场景里的前端成长四阶段
前端·设计模式·架构
依米_1 天前
一文带你剖析 Promise.then all 实现原理,状态机、发布订阅模式完美实现异步编程
javascript·设计模式
jzhwolp1 天前
从基本链表到侵入式链表,体会内核设计思路
c语言·后端·设计模式
李宥小哥1 天前
结构型设计模式1
设计模式
lapiii3581 天前
[智能体设计模式] 第五章 :函数调用
microsoft·设计模式