C# 设计模式——工厂模式

工厂模式简介

工厂模式是我们常用的实例化对象模式了,是用工厂方法代替new 操作的一种模式。是一种创建型模式,所有对象的创造都有一个对象去创造。

在这里插入图片描述
因为工厂模式就相当于创建实例对象的new,我们经常要根据类Class生成实例对象,如A a = new A()工厂模式也是用来创建实例对象的,所以以后new是就要多个心眼,是否可以考虑使用工厂模式,虽然这样做,可能多做一些工作,但也会给你系统带来更大的可扩展性和尽量少的修改量。

多态概括:父类的指针指向子类,而调用子类的方法。

工程模式C# Demo

using System;
using System.Collections;

/// <summary>
/// C# 工程模式Demo    水果店为例
/// </summary>
namespace FactoryDesign
{
    // 定义基类
    public class Fruit
    {
        public virtual void ShowType() { }
    }

    // 定义实体类
    class Apple : Fruit
    {
        public override void ShowType()
        {
            Console.WriteLine("I am an Apple");
        }
    }

    class Orange : Fruit
    {
        public override void ShowType()
        {
            Console.WriteLine("I am a Orange");
        }
    }


    // 创建一个工厂,生成基于给定信息的实体类的对象。
    public class FruitStore
    {
        public Fruit ShowFruitType(string name)
        {
            if (name == "apple")
            {
                return new Apple();
            }

            if (name == "orange")
            {
                return new Orange();
            }
            return new Fruit();
        }
    }

    // 使用该工厂,通过传递类型信息来获取实体类的对象。
    public class Main
    {
        public void ShowMain()
        {
            FruitStore fruitStore = new FruitStore();

            Fruit fruitType1 = fruitStore.ShowFruitType("apple");
            fruitType1.ShowType();

            Fruit fruitType2 = fruitStore.ShowFruitType("orange");
            fruitType2.ShowType();
        }
    }
}

上例UML图

水果

Notes

作为一种创建类模式,在任何需要生成复杂对象的地方,都可以使用工厂方法模式。有一点需要注意的地方就是复杂对象适合使用工厂模式,而简单对象,特别是只需要通过 new 就可以完成创建的对象,无需使用工厂模式。如果使用工厂模式,就需要引入一个工厂类,会增加系统的复杂度。

Unity 工厂模式应用实例

Unity处设置
unity版本: 2019.2.7.f1 Personal
任务:通过工厂模式动态生成Image组件;
在这里插入图片描述
在这里插入图片描述

  1. 生成Canvas画布,并为其添加tag为:MainCanvas;
  2. 创建Resources文件夹,并导入水果素材,素材下载见最下方链接;
  3. 创建Scripts文件夹,新建FruitFactory.cs和UseFactory.cs脚本,并将UseFactory.cs添加给Canvas;

FruitFactory.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FruitFactory
{
    private Dictionary<string, Sprite> fruitDict;
    private Transform parentTransform;
    
    public FruitFactory()
    {
        Initial();
    }


    /// <summary>
    /// 加载商店水果
    /// </summary>
    private void Initial()
    {
        Sprite tmpSprite;
        fruitDict = new Dictionary<string, Sprite>();
        tmpSprite = Resources.LoadAll<Sprite>("Bananas")[0];
        fruitDict.Add("Bananas", tmpSprite);

        tmpSprite = Resources.LoadAll<Sprite>("Cherries")[0];
        fruitDict.Add("Cherries", tmpSprite);

        tmpSprite = Resources.LoadAll<Sprite>("Kiwi")[0];
        fruitDict.Add("Kiwi", tmpSprite);

        tmpSprite = Resources.LoadAll<Sprite>("Melon")[0];
        fruitDict.Add("Melon", tmpSprite);

        parentTransform = GameObject.FindGameObjectWithTag("MainCanvas").transform;           //   获取父级Canvas位置

    }
    // 工厂方法 
    public GameObject CreateFruit(string name, Vector3 pos)
    {
        GameObject tmpObj = new GameObject();
        tmpObj.transform.SetParent(parentTransform, false);
        tmpObj.transform.localPosition = pos;
        tmpObj.transform.SetAsFirstSibling();


        Image tmpImage =tmpObj.AddComponent<Image>();
        tmpImage.sprite = fruitDict[name];

        return tmpObj;
    }
    
}

UseFactory.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UseFactory : MonoBehaviour
{
    private FruitFactory fruitFactory;
    private int count=0;
    private Vector3 pos;
    // Start is called before the first frame update
    void Start()
    {
        fruitFactory = new FruitFactory();
        pos = new Vector3(100, 0, 0);
    }

    // Update is called once per frame
    void Update()
    {
        UserController();
    }

    /// <summary>
    /// 用户通过键盘  Q   W   E    R 键  来控制生成4种水果
    /// </summary>
    private void UserController()
    {
        if ( Input.GetKeyDown(KeyCode.Q))
        {
            fruitFactory.CreateFruit("Bananas", pos*count );
            count++;
        }
        if (Input.GetKeyDown(KeyCode.W))
        {
            fruitFactory.CreateFruit("Cherries", pos * count);
            count++;
        }
        if (Input.GetKeyDown(KeyCode.E))
        {
            fruitFactory.CreateFruit("Kiwi", pos * count);
            count++;
        }
        if (Input.GetKeyDown(KeyCode.R))
        {
            fruitFactory.CreateFruit("Melon", pos * count);
            count++;
        }
    }
}

测试结果:
在这里插入图片描述
资源下载
如有问题,请随时联系我,一个初入unity的萌新

引用与参考

【1】百度百科
【2】菜鸟教程 | 工厂模式

发布了18 篇原创文章 · 获赞 17 · 访问量 2701

猜你喜欢

转载自blog.csdn.net/chasinghope/article/details/104058838