java设计模式之建造模式

来源:互联网 发布:python应用 编辑:程序博客网 时间:2024/05/03 06:40

=======建造模式和之前的工厂模式咋一听,好像啊! =====我的理解建造模式  相当于java语言里的3D打印========

==== 什么时候使用建造模式

====1. 对象内部结构复杂,如一部分可能是对象,甚至对象的一部分

====2. 对象内部属性相互依赖,如 属性一 和属性二  不能同时有值 等等...

====3. 对象内部使用到的属性,在系统中并不容易得到

======================================代码实现===============================

代码主体

/** * @类名 GirlFriend.java * @作者  zx * @创建日期 2016年8月30日 * @描述 一个复杂的对象 * @版本 V 1.0 */public class GirlFriend {//主键private String id;//年龄   大于25岁或者小于22岁 每差1岁扣1分private int age;//地址   国外的加分10   非洲减分10private String address;//得分  初始分数60private int score = 60;//其他资料private String otherData;private GirlFriend(Matchmaker matchmaker) {this.id = matchmaker.id;this.age = matchmaker.age;this.address = matchmaker.address;this.score = matchmaker.score;this.otherData = matchmaker.otherData;}public static class Matchmaker{//主键private String id;//年龄   大于25岁或者小于22岁 每差1岁扣1分private int age;//地址   国外的加分10   非洲减分10private String address;//得分  初始分数60private int score = 60;//其他资料private String otherData;public Matchmaker(String id, int age, String address) {this.id = id;this.age = age;this.address = address;}public Matchmaker setOtherData(String otherData){this.otherData = otherData;return this;}public GirlFriend init(){if(this.age > 25){this.score = this.score - (this.age - 25);}else if(this.age < 22){this.score = this.score - (22 - this.age);}if(this.address.equals("国外")){this.score = this.score + 10;}else if(this.address.equals("非洲")){this.score = this.score - 10;}return new GirlFriend(this);}}public String getId() {return id;}public void setId(String id) {this.id = id;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}public String getOtherData() {return otherData;}public void setOtherData(String otherData) {this.otherData = otherData;}}

测试类

public class TestMain {public static void main(String[] args) {GirlFriend.Matchmaker matchmaker = new GirlFriend.Matchmaker("001", 18, "国外");GirlFriend girlFriend = matchmaker.setOtherData("可爱").init();System.out.println(girlFriend.getScore());}}

===================上面代码  私有了 girlfriend的构造方法  防止客户端 直接调用构造方法======

0 0