簡單工廠模式:由一個工廠對象決定創(chuàng)建出哪一種類的實(shí)例。
創(chuàng)新互聯(lián)主要從事成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)瑞麗,十余年網(wǎng)站建設(shè)經(jīng)驗(yàn),價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):18980820575
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(); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。