设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
geovindu6 小时前
rust: Iterator Pattern
开发语言·后端·设计模式·rust·行为模式·迭代器模
高晶1 天前
ARM 嵌入式 Linux 系统启动流程实战指南
设计模式·程序员
高晶1 天前
BMS 通信开发实战:从 PMBus 协议到数据采集的完整指南
设计模式·程序员
geovindu1 天前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模
电子IT笔记1 天前
老MES登录改造:弱密码和暴破一起治
设计模式
牧瀬クリスだ1 天前
单例模式终极指南:从入门到防破坏
单例模式·设计模式
博风1 天前
9、设计模式应用举例:责任链模式:计算阶乘
设计模式·责任链模式
电子IT笔记1 天前
人走了,记录不能“空白”: MES×HR 离职人员下拉回显实战
设计模式
博风2 天前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式
高晶2 天前
ARM 嵌入式 Linux 系统 U-Boot 开发与移植实战M
设计模式·程序员