java构建模式

原文出自:IT博客吧(http://www.itblog8.cn/java/20130527130.html

构建模式和工厂模式有点类似,不过关注点不同。工厂模式往往只关心你要的是什么,二不关心这个东西的具体细节是什么。而创建模式则关心的是这个东西的具体细节的创建。

构建模式和工厂模式有点类似,不过关注点不同。工厂模式往往只关心你要的是什么,二不关心这个东西的具体细节是什么。而创建模式则关心的是这个东西的具体细节的创建。拿创建人物来说,我们关心的不仅是创建一个人物,还要关心他的性别,肤色和名字,则可以使用构建模式:
1.package builder;
2.
3./**
4. *
5. * DOC 种族角色
6. *
7. */
8.public class Race {
9.
10. private String name;// 名字
11.
12. private String skinColor;// 肤色
13.
14. private String sex;// 性别
15.
16. public String getName() {
17. return this.name;
18. }
19.
20. public void setName(String name) {
21. this.name = name;
22. }
23.
24. public String getSkinColor() {
25. return this.skinColor;
26. }
27.
28. public void setSkinColor(String skinColor) {
29. this.skinColor = skinColor;
30. }
31.
32. public String getSex() {
33. return this.sex;
34. }
35.
36. public void setSex(String sex) {
37. this.sex = sex;
38. }
39.
40.}

1.package builder;
2.
3./**
4. *
5. * DOC 我们关心的不仅仅是创建一个人物,还要关心其特征的创建
6. *
7. */
8.public class RaceBuilder {
9.
10. private Race race;
11.
12. /**
13. * DOC 创建一个种族
14. *
15. * @return
16. */
17. public RaceBuilder builder() {
18. this.race = new Race();
19. return this;
20. }
21.
22. /**
23. * DOC 取名字
24. *
25. * @return
26. */
27. public RaceBuilder setName(String name) {
28. this.race.setName(name);
29. return this;
30. }
31.
32. /**
33. * DOC 选择性别
34. *
35. * @return
36. */
37. public RaceBuilder setSex(String sex) {
38. this.race.setSex(sex);
39. return this;
40. }
41.
42. /**
43. * DOC 选择肤色
44. *
45. * @return
46. */
47. public RaceBuilder setSkinColor(String skinColor) {
48. this.race.setSkinColor(skinColor);
49. return this;
50. }
51.
52. /**
53. *
54. * DOC 返回这个创建好的种族
55. *
56. * @return
57. */
58. public Race create() {
59. return this.race;
60. }
61.}

测试:
1.package builder;
2.
3.public class Main {
4.
5. public static void main(String[] args) {
6. Race race = new RaceBuilder().builder().setName("张三").setSex("男").setSkinColor("白色").create();
7. }
8.
9.}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值