Factory: Choose one more
Function: generate different objects according to different conditions
These different object types are different, but have a common parent class
Case ↓ (Go to the restaurant to choose food)
Factory class
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;
}
}
}
Parent category: rice
Sub-category: noodles/rice/fried rice
Caller ↓
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);
}
}
}
Abstract Factory : Series
(Integrate and abstract multiple concrete factories for management)
Case ↓ (Choose which country's factory will manufacture which kind of weapons from which country)
transfer
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();
}
}
}