簡單工廠模式:由一個工廠對象決定創建出哪一種類的實例。 1.抽象類 2.具體類 3.具體類 4.工廠 5.測試代碼 工廠方法模式:定義一個用於創建對象的介面,讓子類去決定實例化哪一個類。工廠方法使一個類的實例化延遲到其子類。 1.抽象工廠 2.抽象產品和具體實現類。 3.具體工廠,用來具體實現哪個產 ...
簡單工廠模式:由一個工廠對象決定創建出哪一種類的實例。
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(); } }
工廠方法模式:定義一個用於創建對象的介面,讓子類去決定實例化哪一個類。工廠方法使一個類的實例化延遲到其子類。
1.抽象工廠
public interface PeopleFactory{ public People createPeople(); }
2.抽象產品和具體實現類。
public abstract class People{ public abstract void doSth(); } public class Man extends People { @Override public void doSth() { System.out.println("I'm a man,I'm coding."); } } public class Girl extends People { @Override public void doSth() { System.out.println("I'm a girl,I'm eating."); } }
3.具體工廠,用來具體實現哪個產品。
public class ManFactory implements PeopleFactory{ @Override public People createPeople() { return new Man(); } } public class GirlFactory implements PeopleFactory{ @Override public People createPeople() { return new Girl(); } }