色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

java設(shè)計(jì)模式和代碼實(shí)現(xiàn)的

Java 是一門面向?qū)ο蟮木幊陶Z言,設(shè)計(jì)模式是常見的針對(duì)軟件開發(fā)中常見問題的解決方案。針對(duì)不同的問題,有針對(duì)性的設(shè)計(jì)模式可以幫助更好地完成開發(fā)任務(wù)。下面是幾個(gè)常見的 Java 設(shè)計(jì)模式。

1. 單例模式

public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

單例模式保證一個(gè)類只有一個(gè)實(shí)例,并提供一個(gè)訪問它的全局訪問點(diǎn)。上述代碼通過靜態(tài)變量和靜態(tài)方法實(shí)現(xiàn)單例模式。

2. 工廠模式

public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("畫一個(gè)圓形");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("畫一個(gè)正方形");
}
}
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}

工廠模式通過一個(gè)工廠類來創(chuàng)建對(duì)象。上述代碼中 ShapeFactory 類通過傳入的字符串參數(shù)來決定創(chuàng)建哪種 Shape 對(duì)象。

3. 觀察者模式

import java.util.ArrayList;
import java.util.List;
public class Subject {
private Listobservers = new ArrayList<>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
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 Observer(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
public abstract void update();
}
public class BinaryObserver extends Observer {
public BinaryObserver(Subject subject){
super(subject);
}
@Override
public void update() {
System.out.println( "二進(jìn)制字符串: " + Integer.toBinaryString( subject.getState() ) );
}
}
public class OctalObserver extends Observer {
public OctalObserver(Subject subject){
super(subject);
}
@Override
public void update() {
System.out.println( "八進(jìn)制字符串: " + Integer.toOctalString( subject.getState() ) );
}
}
public class HexObserver extends Observer {
public HexObserver(Subject subject){
super(subject);
}
@Override
public void update() {
System.out.println( "十六進(jìn)制字符串: " + Integer.toHexString( subject.getState() ) );
}
}

觀察者模式用于當(dāng)一個(gè)對(duì)象的狀態(tài)發(fā)生改變時(shí),其依賴對(duì)象能夠隨之改變。在上述代碼中,Subject 類發(fā)生狀態(tài)改變時(shí),會(huì)通知觀察者列表中的所有觀察者,觀察者們將根據(jù) Subject 的狀態(tài)來更新自身的狀態(tài)。