簡單工廠模式,顧名思義就是抽象工廠的簡單版~
共有三個環節~ 分別是 抽象產品、具體產品、生產產品~
學習目標: 簡單工廠模式的概念及實務
學習難度: ☆☆☆
using System;
namespace ConsoleApp1
{
abstract class Game //抽象類別定義產品概念
{
public abstract string Name { get; set; }
public abstract int Price { get; set; }
public abstract void Demo();
}
class AOE3 : Game //描述產品的細節
{
public override string Name { get; set; } = "AOE3";
public override int Price { get; set; } = 300;
public override void Demo()
{
Console.WriteLine("AOE3 is Playing");
}
}
static class GameFactory //工廠生產中...
{
public static Game GetGame(string name) //型別是Game,因為要生產Game,所以回傳Game
{
switch (name)
{
case "AOE3":
return new AOE3();
default:
throw new Exception("My factory doesn't' has this game") ;
}
}
}
static class MainProgram //算是Clinet端?!
{
public static void Main()
{
Game AOE3 = GameFactory.GetGame("AOE3");
AOE3.Demo();
}
}
}
參考資料: