Java中常用的5种创建型模式:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。
1. 工厂方法模式(Factory Method Pattern)
场景:当一个类不知道它所需要创建的对象的具体类时,使用工厂方法模式。
interface Product {
void doSomething();
}
class ConcreteProductA implements Product {
@Override
public void doSomething() {
System.out.println("ConcreteProductA is doing something");
}
}
class ConcreteProductB implements Product {
@Override
public void doSomething() {
System.out.println("ConcreteProductB is doing something");
}
}
abstract class Creator {
abstract Product createProduct();
public void someOperation() {
Product product = createProduct();
product.doSomething();
}
}
class CreatorA extends Creator {
@Override
Product createProduct() {
return new ConcreteProductA();
}
}
class CreatorB extends Creator {
@Override
Product createProduct() {
return new ConcreteProductB();
}
}
public class FactoryMethodPatternExample {
public static void main(String[] args) {
Creator creatorA = new CreatorA();
creatorA.someOperation();
Creator creatorB = new CreatorB();
creatorB.someOperation();
}
}
优点:
解耦了产品的创建和使用。
符合开闭原则,新增产品时无需修改现有代码,只需新增具体的创建者和产品。
缺点:
增加了系统中类的个数,复杂度增加。
2. 抽象工厂模式(Abstract Factory Pattern)
场景:当需要创建一系列相关或相互依赖的对象,而无需指定它们具体的类时。
interface Button {
void paint();
}
interface TextField {
void display();
}
class WindowsButton implements Button {
@Override
public void paint() {
System.out.println("Windows Button");
}
}
class WindowsTextField implements TextField {
@Override
public void display() {
System.out.println("Windows TextField");
}
}
class MacButton implements Button {
@Override
public void paint() {
System.out.println("Mac Button");
}
}
class MacTextField implements TextField {
@Override
public void display() {
System.out.println("Mac TextField");
}
}
interface GUIFactory {
Button createButton();
TextField createTextField();
}
class WindowsGUIFactory implements GUIFactory {
@Override
public Button createButton() {
return new WindowsButton();
}
@Override
public TextField createTextField() {
return new WindowsTextField();
}
}
class MacGUIFactory implements GUIFactory {
@Override
public Button createButton() {
return new MacButton();
}
@Override
public TextField createTextField() {
return new MacTextField();
}
}
public class AbstractFactoryPatternExample {
public static void main(String[] args) {
GUIFactory factory;
factory = new WindowsGUIFactory();
Button button = factory.createButton();
TextField textField = factory.createTextField();
factory = new MacGUIFactory();
Button macButton = factory.createButton();
TextField macTextField = factory.createTextField();
}
}
优点:
易于交换产品系列。
方便扩展新的产品系列。
缺点:
难以支持新种类的产品。
3. 单例模式(Singleton Pattern)
场景:当一个类只需要一个实例存在时。
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void doSomething() {
System.out.println("Singleton is doing something");
}
}
public class SingletonPatternExample {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
singleton.doSomething();
}
}
优点:
节省系统资源。
保证全局只有一个实例。
缺点:
违反单一职责原则。
不利于测试。
4. 建造者模式(Builder Pattern)
场景:当创建一个复杂对象,其属性有多个,且构建过程复杂时。
class Computer {
private String cpu;
private String ram;
private String hardDisk;
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public String getRam() {
return ram;
}
public void setRam(String ram) {
this.ram = ram;
}
public String getHardDisk() {
return hardDisk;
}
public void setHardDisk(String hardDisk) {
this.hardDisk = hardDisk;
}
@Override
public String toString() {
return "Computer{" +
"cpu='" + cpu + '\'' +
", ram='" + ram + '\'' +
", hardDisk='" + hardDisk + '\'' +
'}';
}
}
class ComputerBuilder {
private String cpu;
private String ram;
private String hardDisk;
public ComputerBuilder setCpu(String cpu) {
this.cpu = cpu;
return this;
}
public ComputerBuilder setRam(String ram) {
this.ram = ram;
return this;
}
public ComputerBuilder setHardDisk(String hardDisk) {
this.hardDisk = hardDisk;
return this;
}
public Computer build() {
Computer computer = new Computer();
computer.setCpu(cpu);
computer.setRam(ram);
computer.setHardDisk(hardDisk);
return computer;
}
}
public class BuilderPatternExample {
public static void main(String[] args) {
Computer computer = new ComputerBuilder()
.setCpu("Intel i7")
.setRam("16GB")
.setHardDisk("1TB SSD")
.build();
System.out.println(computer);
}
}
优点:
良好的封装性。
建造过程的清晰性。
缺点:
产品必须有共同点,限制了其使用范围。
5. 原型模式(Prototype Pattern)
场景:当对象的创建成本较大,需要通过复制现有对象来创建新对象时。
class Prototype implements Cloneable {
private String name;
public Prototype(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Prototype clone() throws CloneNotSupportedException {
return (Prototype) super.clone();
}
}
public class PrototypePatternExample {
public static void main(String[] args) throws CloneNotSupportedException {
Prototype prototype = new Prototype("Original");
Prototype cloned = prototype.clone();
cloned.setName("Cloned");
System.out.println(prototype.getName());
System.out.println(cloned.getName());
}
}
优点:
性能优化,避免重复的初始化操作。
简化对象创建过程。
缺点:
必须实现 Cloneable 接口,违反了依赖倒置原则。
对深拷贝和浅拷贝的处理需要谨慎。