简单工厂模式:由一个工厂对象决定创建出哪一种类的实例。
1.抽象类
java" id="highlighter_379558">
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(); } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/emoji1213/archive/2017/09/28/7605276.html