Java是一門廣泛應(yīng)用于企業(yè)級(jí)開發(fā)中的編程語(yǔ)言,它支持多種編程范式,如面向?qū)ο缶幊蹋∣OP)、面向切面編程(AOP)、函數(shù)式編程等等。其中,建造者模式和工廠模式是常用于面向?qū)ο缶幊痰脑O(shè)計(jì)模式。下面我們來深入了解一下這兩種模式。
1. 建造者模式
public class Car { private String model; private String engine; private String transmission; private String color; private Car(Builder builder) { model = builder.model; engine = builder.engine; transmission = builder.transmission; color = builder.color; } public static class Builder { private String model; private String engine; private String transmission; private String color; public Builder setModel(String model) { this.model = model; return this; } public Builder setEngine(String engine) { this.engine = engine; return this; } public Builder setTransmission(String transmission) { this.transmission = transmission; return this; } public Builder setColor(String color) { this.color = color; return this; } public Car build() { return new Car(this); } } }
建造者模式是一種用于創(chuàng)建復(fù)雜對(duì)象的創(chuàng)建型設(shè)計(jì)模式。建造者模式將一個(gè)復(fù)雜對(duì)象的創(chuàng)建過程分解為多個(gè)簡(jiǎn)單對(duì)象的構(gòu)建過程,然后按照一定規(guī)則組合起來形成所需的復(fù)雜對(duì)象。在上面的代碼中,我們定義了一個(gè)Car類,使用了建造者模式創(chuàng)建。在Car類內(nèi)部定義了一個(gè)Builder類,用于設(shè)置并構(gòu)造Car對(duì)象,其中,建造過程中需要的參數(shù)進(jìn)行了逐一設(shè)置,最終使用Builder構(gòu)造函數(shù)構(gòu)造出一個(gè)Car對(duì)象。
2. 工廠模式
public interface Shape { void draw(); } public class Circle implements Shape { @Override public void draw() { System.out.println("Circle.draw"); } } public class Rectangle implements Shape { @Override public void draw() { System.out.println("Rectangle.draw"); } } public class Square implements Shape { @Override public void draw() { System.out.println("Square.draw"); } } public class ShapeFactory { public Shape getShape(String shapeType) { if (shapeType == null) { return null; } switch (shapeType) { case "CIRCLE": return new Circle(); case "RECTANGLE": return new Rectangle(); case "SQUARE": return new Square(); default: return null; } } }
工廠模式是一種用于創(chuàng)建對(duì)象的創(chuàng)建型設(shè)計(jì)模式。在工廠模式中,我們定義了一個(gè)用于創(chuàng)建對(duì)象的工廠類,在工廠類內(nèi)部根據(jù)不同的參數(shù)創(chuàng)建不同的對(duì)象。在上面的代碼中,我們定義了Shape接口以及其實(shí)現(xiàn)類,通過ShapeFactory類來創(chuàng)建不同類型的Shape對(duì)象,ShapeFactory類根據(jù)參數(shù)的不同創(chuàng)建不同的Shape對(duì)象。