作者:mobiledu2502885853 | 来源:互联网 | 2024-10-14 21:37
【定义】将构造过程与表示分开,以便于相同的构造过程创建不同的表示。如果对象的构造过程相对复杂,这样的构造模式会非常有效。【实例】我们需要根据需求组装相应的计算机,例如硬盘500G,
【定义】
将构造过程与表示分开,以便于相同的构造过程创建不同的表示。
如果对象的构造过程相对复杂,这样的构造模式会非常有效。
【实例】
我们需要根据需求组装相应的计算机,例如硬盘500G,内存8G,CPU8核等等。
【实现】
定义构造步骤:
interface IBuilder
{
void BuildBody();
void InsertWheels();
void AddHeadlights();
Product GetVehicle();
}
定义一辆车的构造方法:
class Car implements IBuilder
{
private Product product = new Product();
@Override
public void BuildBody()
{
product.Add("This is a body of a Car");
}
@Override
public void InsertWheels()
{
product.Add("4 wheels are added");
}
@Override
public void AddHeadlights()
{
product.Add("2 Headlights are added");
}
@Override
public Product GetVehicle()
{
return product;
}
}
定义摩托车的构造方法:
// Motorcycle is a ConcreteBuilder
class MotorCycle implements IBuilder
{
private Product product = new Product();
@Override
public void BuildBody()
{
product.Add("This is a body of a Motorcycle");
}
@Override
public void InsertWheels()
{
product.Add("2 wheels are added");
}
@Override
public void AddHeadlights()
{
product.Add("1 Headlights are added");
}
@Override
public Product GetVehicle()
{
return product;
}
}
定义产品:
// "Product"
class Product
{
// We can use any data structure that you prefer. We have used LinkedList here.
private LinkedList parts;
public Product()
{
parts = new LinkedList();
}
public void Add(String part)
{
//Adding parts
parts.addLast(part);
}
public void Show()
{
System.out.println("\n Product completed as below :");
for(int i=0;i生产商:
// "Director"
class Director
{
IBuilder myBuilder;
// A series of steps—for the production
public void Construct(IBuilder builder)
{
myBuilder=builder;
myBuilder.BuildBody();
myBuilder.InsertWheels();
myBuilder.AddHeadlights();
}
}
测试: