工厂: 多选一
功能: 据不同的条件产生不同的对象
这些不同的对象类型不同,却具有共同的父类
案例↓ (去餐馆 选择吃的)
工厂类
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();
}
}
}