定义
提供一个接口,用于创建相关或者依赖对象的家族,而不需要明确指定具体类。
UML类图
实现
案例:提供一个创建手机的应用,根据不同的配件类型,生产不同类型的手机(安卓/iPhone)
定义接口
抽象工厂
public interface MobileFactory
{
// 创建CPU
ACPU CreateCPU();
// 创建主板
AMainboard CreateMainboard();
// 创建外壳
AShell CreateShell();
}
CPU
public abstract class ACPU
{
protected string version;
protected string name;
public string Version { get => version; }
public string Name { get => name; }
}
主板
public abstract class AMainboard
{
protected string name;
public string Name { get => name;}
}
外壳
public abstract class AShell
{
protected double screenSize;
protected string color;
public double ScreenSize { get=> screenSize; }
public string Color { get => color; }
}
具体工厂类
安卓工厂
public class AndroidFactory : MobileFactory
{
public ACPU CreateCPU()
{
return new AndroidCPU();
}
public AMainboard CreateMainboard()
{
return new AndroidMainBoard();
}
public AShell CreateShell()
{
return new AndroidShell();
}
}
IOS工厂
public class IOSFactory : MobileFactory
{
public ACPU CreateCPU()
{
return new IOSCPU();
}
public AMainboard CreateMainboard()
{
return new IOSMainboard();
}
public AShell CreateShell()
{
return new IOSShell();
}
}
具体零件类(Member)
安卓
public class AndroidCPU:ACPU
{
public AndroidCPU()
{
this.name = "Qualcomm";
this.version = "860";
}
}
public class AndroidMainBoard:AMainboard
{
public AndroidMainBoard()
{
name = "mainboard for android";
}
}
public class AndroidShell:AShell
{
public AndroidShell()
{
screenSize = 6.0;
color = "black";
}
}
IOS
public class IOSCPU:ACPU
{
public IOSCPU()
{
name = "A";
version = "13";
}
}
public class IOSMainboard:AMainboard
{
public IOSMainboard()
{
name = "mainboard for ios";
}
}
public class IOSShell:AShell
{
public IOSShell()
{
screenSize = 4.7;
color = "red";
}
}
Client
public class Mobile
{
ACPU cpu;
AMainboard mainboard;
AShell shell;
MobileFactory mobileFactory;
public Mobile(MobileFactory mobileFactory)
{
this.mobileFactory = mobileFactory;
}
public void Create()
{
cpu = mobileFactory.CreateCPU();
mainboard = mobileFactory.CreateMainboard();
shell = mobileFactory.CreateShell();
Console.WriteLine($"The mobile is created,with cpu:{cpu.Name+cpu.Version},mainboard:{mainboard.Name},outshell:{shell.ScreenSize},{shell.Color}");
}
}
测试
class Program
{
static void Main(string[] args)
{
MobileFactory mobileFactory = new AndroidFactory();
Mobile android = new Mobile(mobileFactory);
android.Create();
mobileFactory = new IOSFactory();
Mobile iphone = new Mobile(mobileFactory);
iphone.Create();
Console.ReadLine();
}
}
运行结果
The mobile is created,with cpu:Qualcomm860,mainboard:mainboard for android,outshell:6,black
The mobile is created,with cpu:A13,mainboard:mainboard for ios,outshell:4.7,red