设计模式-工厂模式

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

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

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
szm02252 小时前
设计模式-
设计模式
砍光二叉树2 小时前
【设计模式】创建型-抽象工厂模式
设计模式·抽象工厂模式
砍光二叉树4 小时前
【设计模式】创建型-工厂方法模式
设计模式·工厂方法模式
我爱学习_zwj4 小时前
设计模式-2(单例模式与原型模式)
前端·javascript·设计模式
砍光二叉树5 小时前
【设计模式】创建型-单例模式
单例模式·设计模式
我爱学习_zwj5 小时前
设计模式-3(装饰器模式)
前端·设计模式·装饰器模式
文心快码BaiduComate20 小时前
Comate内置模型已支持 MiniMax-M2.7!
设计模式·程序员·前端框架
console.log('npc')21 小时前
Cursor,Trae,Claude Code如何协作生产出一套前后台app?
前端·人工智能·react.js·设计模式·ai·langchain·ai编程
czxyvX1 天前
C++ - 基于多设计模式下的同步&异步日志系统
c++·设计模式
蒸蒸yyyyzwd1 天前
设计模式之美学习笔记
笔记·学习·设计模式