【注意】最后更新于 December 15, 2017,文中内容可能已过时,请谨慎使用。
本文来介绍下java设计模式之工厂模式?
在王者峡谷里,有一群快乐的蓝精....召唤师,他们快乐又调皮。
他们分为战士,射手,法师,刺客,肉等。为了创建他们,开发人员一个有一个的new好麻烦啊!
一拍大腿,建个厂子吧!
批量生产,批量销售,走向全世界!
我们都知道,召唤师有三个技能(大乔等人请走开!)
1
2
3
4
5
6
7
|
package top.txiner.factory;
public interface Summoner {
public void skillOne();
public void skillTwo();
public void skillThree();
}
|
就可以进行战场厮杀啦!
好,我们来实现个adc的类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package top.txiner.factory;
public class ADC implements Summoner {
public void skillOne() {
System.out.println("I am adc and I can shoot you");
}
public void skillTwo() {
System.out.println("I am adc and I can attack you in a long distance");
}
public void skillThree() {
System.out.println("I am adc and I am a little weak");
}
}
|
再来个刺客的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package top.txiner.factory;
public class Assassin implements Summoner {
public void skillOne() {
System.out.println("I am assassin and I am flexible");
}
public void skillTwo() {
System.out.println("I am assassin and I can kill adc");
}
public void skillThree() {
System.out.println("I am assassin and I am master");
}
}
|
最后来个战士的,打爆全场!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package top.txiner.factory;
public class Soldier implements Summoner {
public void skillOne() {
System.out.println("I am soldier and I am invincible");
}
public void skillTwo() {
System.out.println("I am soldier and I am unbeatable");
}
public void skillThree() {
System.out.println("I am soldier and I am most powerful");
}
}
|
好了啊!磨具造好了,把生产线建设一下!
输入要创建什么类型的英雄,就输出出来吧。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package top.txiner.factory;
public class SummonerFactory {
public static Summoner createSummoner(Class c) {
Summoner summoner = null;
try {
summoner = (Summoner) Class.forName(c.getName()).newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return summoner;
}
}
|
OK!完美!
来,造个召唤师看看
1
2
3
4
5
6
7
8
|
package top.txiner.factory;
public class Designer {
public static void main(String[] args) {
Summoner summoner=SummonerFactory.createSummoner(Soldier.class);
summoner.skillOne();
}
}
|
很好,我们成功的生产出了战士!
似乎不难嘛!
----------分割线---------
看了这几个生产模式,不知道大家有没有发现,设计模式差不都都是以interface为基础而创建的!
实际上好多一直在这说没什么用,还是得靠勤加练习,多做项目才有收获!