java实现23种设计模式之建造者模式
举一个发送邮件和短信的例子
package com.ceshi3; /** * 举一个发送邮件和短信的例子 * @author Administrator * */ public interface Sender { public void Send(); }
package com.ceshi3; public class MailSender implements Sender{ @Override public void Send() { System.out.println("this is mail sender"); } }
package com.ceshi3; public class SmsSender implements Sender{ @Override public void Send() { System.out.println("this is sms sender"); } }
建造者类:
package com.ceshi3; import java.util.ArrayList; import java.util.List; public class Builder { private List<Sender> list = new ArrayList<Sender>(); public List<Sender> produceMailSender(int count){ for(int i=0; i<count; i++){ list.add(new MailSender()); } return list; } public List<Sender> produceSmsSender(int count){ for(int i=0; i<count; i++){ list.add(new SmsSender()); } return list; } }
测试
package com.ceshi3; import java.util.List; public class Test { public static void main(String[] args) { Builder builder = new Builder(); List<Sender> list = builder.produceMailSender(10); for (Sender sender : list) { sender.Send(); } } }
建造者模式将很多功能集成到一个类里,这个类可以创造出比较复杂的东西。用的比较多,工厂模式适用于单个;
建造者是为了使用多个对象集中在一起建造一个比较复杂的功能;