设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
geovindu33 分钟前
python: N-Barrier Pattern
开发语言·python·设计模式·屏障模式
basketball6163 小时前
设计模式入门:2. 工厂模式详解 C++实现
开发语言·c++·设计模式
basketball6163 小时前
设计模式入门:1. 单例模式详解 C++实现
c++·单例模式·设计模式
小马爱打代码3 小时前
Spring源码中的设计模式实战:从理论到源码的深度解析
java·spring·设计模式
WiLL4 小时前
AI 时代下的 SaaS: Skill As A Service (一)
设计模式·架构
basketball6166 小时前
设计模式入门:3. 装饰器模式详解 C++实现
c++·设计模式·装饰器模式
咖啡八杯6 小时前
GoF设计模式——装饰模式
java·算法·设计模式·装饰器模式
lqqjuly1 天前
设计模式:理论、架构与 C++ 实现—SOLID原则到23 种经典模式
c++·设计模式·架构
老码观察1 天前
设计模式实战解读(九):责任链模式——流水线上层层把关的艺术
java·设计模式·责任链模式
workflower3 天前
具身智能研究对象:物理交互中的智能行为
设计模式·动态规划·软件工程·软件构建·scrum