Java中的設計模式詳解
大家好,我是微賺淘客系統3.0的小編,是個冬天不穿秋褲,天冷也要風度的程式猿!
單例模式
在實際開發中,經常會遇到需要保證一個類只有一個例項的情況。單例模式透過私有化構造方法和靜態方法來確保只有一個例項被建立。以下是一個示例:
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()));
}
}
著作權歸聚娃科技微賺淘客系統開發者團隊,轉載請註明出處!