欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 八卦 > 建造者模式

建造者模式

2024/11/30 14:49:22 来源:https://blog.csdn.net/qq_40280043/article/details/139618877  浏览:    关键词:建造者模式

  建造者模式适用于需要生成的产品对象有复杂的内部结构。

 1 //产品2 public class AirShip {3     private Engine engine;    //发动机4     private Cabin cabin;    //机舱5     private Excape excape;    //逃生舱6     public Engine getEngine() {7         return engine;8     }9     public void setEngine(Engine engine) {
10         this.engine = engine;
11     }
12     public Cabin getCabin() {
13         return cabin;
14     }
15     public void setCabin(Cabin cabin) {
16         this.cabin = cabin;
17     }
18     public Excape getExcape() {
19         return excape;
20     }
21     public void setExcape(Excape excape) {
22         this.excape = excape;
23     }
24 }
25 class Engine{
26     String name;
27 }
28 class Cabin{
29     String name;
30 }
31 class Excape{
32     String name;
33 }
1 //产品建造
2 public interface AirShipBuilder {
3     Engine createEngine();
4     Cabin createCabin();
5     Excape createExcape();
6 }
1 //指挥者
2 public interface Director {
3     AirShip createAirship();
4 }
 1 //具体的指挥者2 public class SxtDirector implements Director{3     AirShipBuilder builder;4     //根据不同的建造者5     public SxtDirector(AirShipBuilder builder) {6         this.builder = builder;7     }8     //相同的安装顺序9     @Override
10     public AirShip createAirship() {
11         AirShip ship = new AirShip();
12         ship.setCabin(builder.createCabin());
13         ship.setEngine(builder.createEngine());
14         ship.setExcape(builder.createExcape());
15         return ship;
16     }
17 }
//具体的建造者
public class SxtAirShipBuilder implements AirShipBuilder{@Overridepublic Engine createEngine() {System.out.println("engine is building");return new Engine();}@Overridepublic Cabin createCabin() {System.out.println("cabin is building");return new Cabin();}@Overridepublic Excape createExcape() {System.out.println("excape is building");return new Excape();}
}
1 //用户只需要与指挥者和建造者打交道就可以得到结构复杂的产品 
2 public class BuilderDemo {
3     public static void main(String[] args) {
4         AirShipBuilder bu = new SxtAirShipBuilder();
5         AirShip ship = new SxtDirector(bu).createAirship();
6     }
7 }

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com