java建造者模式(笔记)

2022/1/11 14:04:16

本文主要是介绍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();
	}

}

在这里插入图片描述



这篇关于java建造者模式(笔记)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程