1、单例模式(Singleton Pattern):
public class Singleton {
private static Singleton instance;
private Singleton() {
// 私有构造函数
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
确保一个类只有一个实例,并提供全局访问点。
2、工厂模式(Factory Pattern):
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
public class ShapeFactory {
public Shape createShape(String type) {
if (type.equals("circle")) {
return new Circle();
} else if (type.equals("rectangle")) {
return new Rectangle();
}
return null;
}
}
通过一个工厂类来创建对象,隐藏对象的创建逻辑。
3、抽象工厂模式(Abstract Factory Pattern):
public interface Button {
void click();
}
public interface Checkbox {
void check();
}
public class WindowsButton implements Button {
@Override
public void click() {
System.out.println("Windows button clicked");
}
}
public class WindowsCheckbox implements Checkbox {
@Override
public void check() {
System.out.println("Windows checkbox checked");
}
}
public class MacButton implements Button {
@Override
public void click() {
System.out.println("Mac button clicked");
}
}
public class MacCheckbox implements Checkbox {
@Override
public void check() {
System.out.println("Mac checkbox checked");
}
}
public interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
public class WindowsFactory implements GUIFactory {
@Override
public Button createButton() {
return new WindowsButton();
}
@Override
public Checkbox createCheckbox() {
return new WindowsCheckbox();
}
}
public class MacFactory implements GUIFactory {
@Override
public Button createButton() {
return new MacButton();
}
@Override
public Checkbox createCheckbox() {
return new MacCheckbox();
}
}
提供一个接口,用于创建相关或依赖对象的家族,而不需要指定具体的类。
4、建造者模式(Builder Pattern):
public class Car {
private String make;
private String model;
private int year;
private int price;
private Car(Builder builder) {
this.make = builder.make;
this.model = builder.model;
this.year = builder.year;
this.price = builder.price;
}
public static class Builder {
private String make;
private String model;
private int year;
private int price;
public Builder(String make, String model) {
this.make = make;
this.model = model;
}
public Builder setYear(int year) {
this.year = year;
return this;
}
public Builder setPrice(int price) {
this.price = price;
return this;
}
public Car build() {
return new Car(this);
}
}
}
通过一步一步的方式构建复杂对象,使得同样的构建过程可以创建不同的表示。