java建造者模式(笔记)

java建造者模式(笔记),第1张

java建造者模式(笔记)

定义:指将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示。即组装的复杂对象没有变化,里面的拆分对象可以自定义替换。

一、需求:需要创建一个手机类实例,手机类包含了cpu、cell(电池)、pcb(电路板)三个全局变量。

结构:
建造者抽象类
建造者实现类
指挥类
产品类

package com.bycotrun.builder;

//电池
public class Cell {

	public Cell() {
		System.out.println("电池构造方法");
	}

}

package com.bycotrun.builder;

public class Cpu {
	public Cpu() {
		System.out.println("cpu构造方法");
	}
}

package com.bycotrun.builder;

//电路板
public class Pcb {

	public Pcb() {
		System.out.println("电路板构造方法");
	}

}

package com.bycotrun.builder;

//建筑者抽象类
public abstract class Builder {

	protected Phone2 phone = new Phone2();

	public abstract void setCpu();

	public abstract void setCell();

	public abstract void setPcb();

	public Phone2 getPhone() {
		return phone;
	};
}

package com.bycotrun.builder;

//苹果手机建造者实现类
public class AppBuilder extends Builder {

	@Override
	public void setCpu() {
		super.phone.setCpu(new Cpu());
	}

	@Override
	public void setCell() {
		super.phone.setCell(new Cell());
	}

	@Override
	public void setPcb() {
		super.phone.setPcb(new Pcb());
	}

}

package com.bycotrun.builder;

//指挥者类
public class Director {

	private Builder builder;

	public Director(Builder builder) {
		this.builder = builder;
	}

	public Phone2 getPhone() {
		builder.setCell();
		builder.setCpu();
		builder.setPcb();
		return builder.getPhone();
	}

	public static void main(String[] args) {
		Director director = new Director(new AppBuilder());
		Phone2 phone = director.getPhone();
		System.out.println(phone);
	}

}

二、当创建对象有很多入参时,可以使用链式编程,提高代码可读性高

package com.bycotrun.builder;

//电池
public class Cell {

	public Cell() {
		System.out.println("电池构造方法");
	}

}

package com.bycotrun.builder;

public class Cpu {
	public Cpu() {
		System.out.println("cpu构造方法");
	}
}

package com.bycotrun.builder;

//电路板
public class Pcb {

	public Pcb() {
		System.out.println("电路板构造方法");
	}

}

package com.bycotrun.builder;

//电话
public class Phone {
	private Cell cell;// 电池
	private Cpu cpu;// cup
	private Pcb pcb;// 电路板

	private Phone(Builder builder) {// 构造函数
		System.out.println("手机构造方法");
		this.cell = builder.cell;
		this.cpu = builder.cpu;
		this.pcb = builder.pcb;
	}

	public static class Builder {// 静态内部类
		private Cell cell;
		private Cpu cpu;
		private Pcb pcb;

		public Builder cell(Cell cell) {
			this.cell = cell;
			return this;
		}

		public Builder cpu(Cpu cpu) {
			this.cpu = cpu;
			return this;
		}

		public Builder pcb(Pcb pcb) {
			this.pcb = pcb;
			return this;
		}

		// 构建Phone对象
		public Phone build() {
			return new Phone(this);
		}
	}

	public static void main(String[] args) {
		//创建对象
		Phone phone = new Phone.Builder()
		             .cell(new Cell())
		             .cpu(new Cpu())
		             .pcb(new Pcb())
		             .build();
	}

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5703649.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存