Java中的设计模式详解
单例模式
在实际开发中,经常会遇到需要保证一个类只有一个实例的情况。单例模式通过私有化构造方法和静态方法来确保只有一个实例被创建。以下是一个示例:
package cn.juwatech.designpatterns;
public class Singleton {
private static Singleton instance;
private Singleton() {
// 私有化构造方法
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
工厂模式
工厂模式用于封装对象的创建逻辑,客户端通过工厂类来获取所需的对象实例,而无需关心对象的具体创建过程。以下是一个简单的工厂模式示例:
package cn.juwatech.designpatterns;
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 ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
} else if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
return null;
}
}
观察者模式
观察者模式定义了对象之间的一对多依赖关系,当一个对象状态发生改变时,其相关依赖对象都会得到通知并自动更新。下面是一个观察者模式的简单实现:
package cn.juwatech.designpatterns;
import java.util.ArrayList;
import java.util.List;
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void attach(Observer observer) {
observers.add(observer);
}
public void notifyAllObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
public class BinaryObserver extends Observer {
public BinaryObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println("Binary String: " + Integer.toBinaryString(subject.getState()));
}
}
public class OctalObserver extends Observer {
public OctalObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println("Octal String: " + Integer.toOctalString(subject.getState()));
}
}