最近尝试性地在牛客上笔试了一下,感觉除了上课所学的设计模式以外,公司笔试还会有要求掌握其他虽然不常用但是重要的设计模式
什么是构建者模式
将一个复杂对象的构建与他的表示分离,使得同样的构建过程可以创建不同的表示 隐藏了复杂对象的创建过程,把他复杂对象的创建过程加以抽象,通过子类继承或重载
UML图
共享单车为例子的代码
转自:https://www.jianshu.com/p/3d1c9ffb0a28 原始单车对象(product):
public class Bike {
private IFrame frame;
private ISeat seat;
private ITire tire;
public IFrame getFrame ( ) {
return frame;
}
public void setFrame ( IFrame frame) {
this . frame = frame;
}
public ISeat getSeat ( ) {
return seat;
}
public void setSeat ( ISeat seat) {
this . seat = seat;
}
public ITire getTire ( ) {
return tire;
}
public void setTire ( ITire tire) {
this . tire = tire;
}
}
public abstract class Builder {
abstract void buildFrame ( ) ;
abstract void buildSeat ( ) ;
abstract void buildTire ( ) ;
abstract Bike createBike ( ) ;
}
实体构建者摩拜,ofo(concreteBuilder)
public class MobikeBuilder extends Builder {
private Bike mBike = new Bike ( ) ;
@Override
void buildFrame ( ) {
mBike. setFrame ( new AlloyFrame ( ) ) ;
}
@Override
void buildSeat ( ) {
mBike. setSeat ( new DermisSeat ( ) ) ;
}
@Override
void buildTire ( ) {
mBike. setTire ( new SolidTire ( ) ) ;
}
@Override
Bike createBike ( ) {
return mBike;
}
}
public class OfoBuilder extends Builder {
private Bike mBike = new Bike ( ) ;
@Override
void buildFrame ( ) {
mBike. setFrame ( new CarbonFrame ( ) ) ;
}
@Override
void buildSeat ( ) {
mBike. setSeat ( new RubberSeat ( ) ) ;
}
@Override
void buildTire ( ) {
mBike. setTire ( new InflateTire ( ) ) ;
}
@Override
Bike createBike ( ) {
return mBike;
}
}
public class Director {
private Builder mBuilder = null ;
public Director ( Builder builder) {
mBuilder = builder;
}
public Bike construct ( ) {
mBuilder. buildFrame ( ) ;
mBuilder. buildSeat ( ) ;
mBuilder. buildTire ( ) ;
return mBuilder. createBike ( ) ;
}
}
public class Click {
public static void main ( String[ ] args) {
showBike ( new OfoBuilder ( ) ) ;
showBike ( new MobikeBuilder ( ) ) ;
}
private void showBike ( Builder builder) {
Director director = new Director ( builder) ;
Bike bike = director. construct ( ) ;
bike. getFrame ( ) . frame ( ) ;
bike. getSeat ( ) . seat ( ) ;
bike. getTire ( ) . tire ( ) ;
}
}
优缺点
优点
实例建造者之间是相互独立的(摩拜和ofo),有利于系统的扩展 构建者模式可以使得客户端不必知道产品内部的细节,如摩拜里面单车的车轮选择什么品牌 构建者之间相互独立,使得可以对建造过程逐渐细化,而不对其他模块产生影响
缺点
如果产品之间差异性太大,则不适合使用建造者模式 如果产品内部变化复杂,则需要定义许多具体的建造者来实现这种变化,导致系统庞大