设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
老码观察2 小时前
设计模式实战解读(八):代理模式——控制访问的隐形中间层
设计模式·代理模式
我爱cope3 小时前
【Agent智能体12 | 反思设计模式-使用外部反馈】
人工智能·设计模式·语言模型·职场和发展
geovindu3 小时前
python: Bounded Parallelism Pattern
开发语言·python·设计模式·有界并行模式
我爱cope4 小时前
【Agent智能体11 | 反思设计模式-评估反射的影响的方法】
人工智能·设计模式·语言模型·职场和发展
nnsix4 小时前
设计模式 - 迭代器模式 笔记
笔记·设计模式·迭代器模式
IT策士4 小时前
第 23篇 k8s之Pod:多容器 Pod 与设计模式(Sidecar 等)
设计模式·容器·kubernetes
qq_2975746721 小时前
设计模式系列文章(基础篇第 11 篇):模板方法模式——定义算法骨架,实现代码复用与流程统一
算法·设计模式·模板方法模式
狂人开飞机1 天前
01. 工厂模式(Factory Pattern)
设计模式·c#
阿狸猿1 天前
论软件设计模式及其应用
设计模式
workflower1 天前
具身智能-三层结构
人工智能·设计模式·动态规划·软件工程·scrum