The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
学习目标: 抽象工厂模式的概念及实务
学习难度: ☆☆☆
using System;namespace ConsoleApp1{ abstract class GameFactory //抽象工厂 { public abstract RTS CreateRTS(); public abstract FPS CreateFPS(); } class Department : GameFactory //具体工厂(部门) { public override RTS CreateRTS() { Console.WriteLine("AOE3已生产"); return new AOE3(); } public override FPS CreateFPS() { Console.WriteLine("CSO已生产"); return new CSO(); } } abstract class RTS //抽象产品 { public abstract string name { get; set; } public abstract int price { get; set; } public abstract void Demo(); } class AOE3 : RTS //具体产品 { public override string name { get; set; } = "AOE3"; public override int price { get; set; } = 300; public override void Demo() { Console.WriteLine("This is AOE3 game"); } } abstract class FPS //抽象产品 { public abstract string name { get; set; } public abstract int price { get; set; } public abstract void Demo(); } class CSO : FPS //具体产品 { public override string name { get; set; } = "CSO"; public override int price { get; set; } = 100; public override void Demo() { Console.WriteLine("This is CSO game"); } } class Steam //客户端(串接工厂and产品) { public RTS AOE3; public FPS CSO; public Steam(GameFactory factory) //Steam上架... { AOE3 = factory.CreateRTS(); CSO = factory.CreateFPS(); } } class MainProgram { public static void Main() { GameFactory department = new Department(); Steam steam = new Steam(department); } }}
参考资料:
https://www.dofactory.com/net/abstract-factory-design-pattern