這篇文章主要介紹了java設計模式之簡單工廠模式的相關資料,具有一定的參考價值,有興趣的小夥伴們可以參考一下
簡單工廠模式:由一個工廠物件決定建立出哪一種類別的實例。
1.抽象類別
public abstract class People { public abstract void doSth(); }
#2.具體類別
public class Man extends People{ @Override public void doSth() { System.out.println("I'm a man,I'm coding."); } }
3.具體類別
public class Girl extends People{ @Override public void doSth() { System.out.println("I'm a girl,I'm eating."); } }
4.工廠
public class PeopleFactory { public static People getSpecificPeople(String type){ if("A-Man".equals(type)){ return new Man(); }else if("B-Girl".equals(type)){ return new Girl(); }else { return null; } } }
5.測試代碼
public class PeopleTestDemo { public static void main(String[] args) { People man = PeopleFactory.getSpecificPeople("A-Man"); Objects.requireNonNull(man,"对象不存在."); man.doSth(); People girl = PeopleFactory.getSpecificPeople("B-Girl"); Objects.requireNonNull(girl,"对象不存在"); girl.doSth(); People foodie = PeopleFactory.getSpecificPeople("Foodie"); Objects.requireNonNull(foodie,"对象不存在"); foodie.doSth(); } }
以上是Java實作簡單工廠模式詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!