簡單工廠模式:由一個工廠對象決定創(chuàng)建出哪一種類的實(shí)例。
1.抽象類
1
2
3
|
public abstract class People { public abstract void doSth(); } |
2.具體類
1
2
3
4
5
6
|
public class Man extends People{ @Override public void doSth() { System.out.println( "I'm a man,I'm coding." ); } } |
3.具體類
1
2
3
4
5
6
7
|
public class Girl extends People{ @Override public void doSth() { System.out.println( "I'm a girl,I'm eating." ); } } |
4.工廠
1
2
3
4
5
6
7
8
9
10
11
12
|
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.測試代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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í)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/emoji1213/archive/2017/09/28/7605276.html