Unity学习笔记:设计模式-工厂 抽象工厂

    工厂:                        多选

功能: 据不同的条件产生不同的对象

           这些不同的对象类型不同,却具有共同的父类

案例↓ (去餐馆 选择吃的)

工厂类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dp1_FactoryMethod
{
    public class 饭馆
    {
        public static 饭 CreatConObj(int i)
        {
            饭 con=null;
            switch(i)
            {
                case 1:
                    con = new 米饭();
                    break;
                case 2:
                    con = new 面条();
                    break;
                case 3:
                    con = new 炒饭();
                    break;

            }
            return con;

        }

    }
}

父类:饭

子类:面条/米饭/炒饭

调用端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace dp1_FactoryMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            //方法1:常规写法
            //米饭 conObj = new 米饭();
            //炒饭 conObj = new 炒饭();
            //方法2:工厂方法
            饭 conObj = 饭馆.CreatConObj(3);
        }
    }
}

 

抽象工厂系列   

(将多个具体工厂整合 抽象出来管理) 

案例↓(选择哪个国家工厂 就制造哪个国家 的哪种武器)

调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace dp2_Abstract_Factory
{
    class Program
    {
        static void Main(string[] args)
        {
            //选择中国生产
            抽象工厂 factory = new 中国工厂();
            factory.国家 = "中国";
            坦克 zhushi=factory.生产坦克();
            战斗机  cai=factory.生产战斗机();

            Console.WriteLine(factory.国家);
            Console.WriteLine(zhushi);
            Console.WriteLine(cai);

            Console.ReadLine();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值