--- tags: Creational Patterns --- # 簡單工廠模式 Simple Factory 又稱靜態工廠模式(Static Factory),傳入不同的參數取得不同的類別物件。 被創建的實例通常都具有共同的父類。 **程式說明** ```java= //以冒險者作為產品介面(Product),實作射手與鬥士兩種冒險者(ConcreteProduct)。 public interface Adventurer{ //敘述是哪種冒險者 String getType(); } public class Archer implements Adventurer{ @override public string getType(){ System.out.println("我是射手"); } } public class Warrior implements Adventurer{ @override public string getType(){ System.out.println("我是鬥士"); } } //以冒險者訓練營作為簡單工廠(Simple Factor),輸入參數以創建冒險者 public class TrainingCamp{ public static Adventurer TrainAdventurer(String type){ switch(type){ case "archer":{ System.out.println("訓練一個射手"); return new Archer(); } case "warrior":{ System.out.println("訓練一個鬥士"); return new Warrior(); } default: return null; } ``` > [name=耀宗]
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up