建造者模式(Builder)
构件者模式:当某个类的组件构成复杂,我们将组件的制造与装配分开来。
组件的制造者叫做Builder
组件的装配者叫做Director
比如:手机由屏幕、电池、主板三个子组件构成,那我把制作子组件的人叫做PhoneBuilder,把组装它们成为手机的人叫做PhoneDirector。
定义组装者接口和构建者接口后,通过不同的实现类,可以制作不同的手机,(包括组件的不同和组装方式不同)。
实现思路:
(LurenjiaPhoneBuilder)构建者制作手机的组件(Screen、Battery、Cpu),LurenjiaPhoneDirector(组装者)从(LurenjiaPhoneBuilder)构建者那拿到子组件,Client从LurenjiaPhoneDirector那拿到手机。
手机 Phone :
public class Phone { private Screen screen;//屏幕 private Battery battery;//电池 private Cpu cpu;//主板 public Phone() { } public Screen getScreen() { return screen; } public void setScreen(Screen screen) { this.screen = screen; } public Battery getBattery() { return battery; } public void setBattery(Battery battery) { this.battery = battery; } public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } }
屏幕 Screen :
public class Screen { private String name; public Screen(String name){ this.name=name; } public String getName() { return name;} }
电池 Battery :
public class Battery { private String name; public Battery(String name){ this.name=name;} public String getName() { return name; } }
主板 Cpu :
public class Cpu { private String name; public Cpu(String name){ this.name=name; } public String getName() { return name; } }
构建者接口 PhoneBuilder :实现类需要实现创建屏幕、电池、主板
public interface PhoneBuilder { Screen creatScreen(); Battery creatBattery(); Cpu creatCpu(); }
构建者 LurenjiaPhoneBuilder :
public class LurenjiaPhoneBuilder implements PhoneBuilder{ @Override public Screen creatScreen() { return new Screen("屏幕 by Lurenjia"); } @Override public Battery creatBattery() { return new Battery("电池 by Lurenjia"); } @Override public Cpu creatCpu() { return new Cpu("主板 by Lurenjia"); } }
组建者接口 PhoneDirector 及其实现类 LurenjiaPhoneDirector:
public interface PhoneDirector { Phone creatPhone();//组装一台手机 } /** * 路人甲组装厂 */ class LurenjiaPhoneDirector implements PhoneDirector{ private PhoneBuilder phoneBuilder;//从组件制作者拿组件 public LurenjiaPhoneDirector(PhoneBuilder phoneBuilder) { this.phoneBuilder = phoneBuilder; } @Override public Phone creatPhone() { Phone phone = new Phone(); phone.setBattery(phoneBuilder.creatBattery()); phone.setScreen(phoneBuilder.creatScreen()); phone.setCpu(phoneBuilder.creatCpu()); return phone; } }
客户来咯:
public class Client { //我想要个手机,要Lurenjia制作的组件,Lurenjia组装的那种! public static void main(String[] args) { //1.通过拿货来源,创建一个组装者。 PhoneDirector pd = new LurenjiaPhoneDirector(new LurenjiaPhoneBuilder()); //2.组装一台手机 Phone phone = pd.creatPhone(); //3.看看配件是什么货色 System.out.println(phone.getBattery().getName()); System.out.println(phone.getCpu().getName()); System.out.println(phone.getScreen().getName()); } }
运行结果: