Commit b9ee30ea by yuwei

Java设计模式

parent 651ef128
package cn.datax.learning.design.patterns.creational;
/**
* 建造者模式(Builder Pattern)
*/
public class BuilderPattern {
public static void main(String[] args) {
MyDate myDate = new MyDate();
IDateBuilder builder;
builder = new DateBuilder1(myDate);
String date1 = new Derector(builder).getDate(2066, 3, 6);
System.out.println(date1);
builder = new DateBuilder2(myDate);
String date2 = new Derector(builder).getDate(2067, 4, 6);
System.out.println(date2);
}
}
//首先定义一个产品类
class MyDate {
String Date;
}
//然后抽象生成器,描述生成器的行为
interface IDateBuilder {
IDateBuilder buildDate(int y, int m, int d);
String date();
}
//接下来是具体生成器,一个以“-”分割年月日,另一个使用空格:
class DateBuilder1 implements IDateBuilder {
private MyDate myDate;
public DateBuilder1(MyDate myDate) {
this.myDate = myDate;
}
@Override
public IDateBuilder buildDate(int y, int m, int d) {
myDate.Date = y + "-" + m + "-" + d;
return this;
}
@Override
public String date() {
return myDate.Date;
}
}
//具体生成器
class DateBuilder2 implements IDateBuilder {
private MyDate myDate;
public DateBuilder2(MyDate myDate) {
this.myDate = myDate;
}
@Override
public IDateBuilder buildDate(int y, int m, int d) {
myDate.Date = y + " " + m + " " + d;
return this;
}
@Override
public String date() {
return myDate.Date;
}
}
//接下来是指挥官,向用户提供具体的生成器:
class Derector {
private IDateBuilder builder;
public Derector(IDateBuilder builder) {
this.builder = builder;
}
public String getDate(int y, int m, int d) {
builder.buildDate(y, m, d);
return builder.date();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment