首頁  >  文章  >  Java  >  深入了解常用的7種Java設計模式

深入了解常用的7種Java設計模式

王林
王林原創
2023-12-23 13:01:10720瀏覽

深入了解常用的7種Java設計模式

了解Java設計模式:常用的7種設計模式簡介,需要具體程式碼範例

Java設計模式是一種解決軟體設計問題的通用解決方案,它提供了一套被廣泛接受的設計想法與行為準則。設計模式幫助我們更好地組織和規劃程式碼結構,使得程式碼具有更好的可維護性、可讀性和可擴展性。在本文中,我們將介紹Java中常用的7種設計模式,並提供對應的程式碼範例。

  1. 單例模式(Singleton Pattern):
    單例模式保證一個類別只有一個實例,並提供一個全域存取點。這在需要共享資源或限制物件個數的場景中非常有用。下面是一個單例模式的程式碼範例:
public class Singleton {

    private static Singleton instance;

    private Singleton() {
        // 私有构造函数,防止外部实例化
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  1. 工廠模式(Factory Pattern):
    工廠模式透過一個工廠類別來建立對象,封裝了物件的建立過程。這可以隱藏物件的具體實作細節,使得客戶端的程式碼更加簡潔和可擴展。下面是一個工廠模式的程式碼範例:
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;
        }
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        }
        return null;
    }
}
  1. #觀察者模式(Observer Pattern):
    觀察者模式定義了一種一對多的依賴關係,當一個對象的狀態改變時,依賴它的其他物件將自動更新。這在事件驅動、發布-訂閱,以及GUI開發中非常有用。以下是觀察者模式的程式碼範例:
import java.util.ArrayList;
import java.util.List;

public class Subject {
    private List<Observer> observers = 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 abstract void update();
}

public class BinaryObserver extends Observer {
    public BinaryObserver(Subject subject) {
        this.subject = subject;
        this.subject.attach(this);
    }

    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);
    }

    public void update() {
        System.out.println("Octal String: " + Integer.toOctalString(subject.getState()));
    }
}

public class HexObserver extends Observer {
    public HexObserver(Subject subject) {
        this.subject = subject;
        this.subject.attach(this);
    }

    public void update() {
        System.out.println("Hex String: " + Integer.toHexString(subject.getState()));
    }
}

public class ObserverPatternDemo {
    public static void main(String[] args) {
        Subject subject = new Subject();
        new BinaryObserver(subject);
        new OctalObserver(subject);
        new HexObserver(subject);

        System.out.println("First state change: 15");
        subject.setState(15);
        System.out.println("Second state change: 10");
        subject.setState(10);
    }
}
  1. 建造者模式(Builder Pattern):
    建造者模式透過將物件的建構過程分離,使得相同的建構過程可用於建立不同的表示。這可以提高程式碼的靈活性和可讀性,並且可以避免建置參數過多的問題。以下是一個建造者模式的程式碼範例:
public class Computer {
    private String cpu;
    private String memory;
    private String disk;
    // 省略其他属性和方法
}

public interface ComputerBuilder {
    ComputerBuilder setCpu(String cpu);
    ComputerBuilder setMemory(String memory);
    ComputerBuilder setDisk(String disk);
    Computer build();
}

public class BasicComputerBuilder implements ComputerBuilder {
    private Computer computer;

    public BasicComputerBuilder() {
        computer = new Computer();
    }

    public ComputerBuilder setCpu(String cpu) {
        computer.setCpu(cpu);
        return this;
    }

    public ComputerBuilder setMemory(String memory) {
        computer.setMemory(memory);
        return this;
    }

    public ComputerBuilder setDisk(String disk) {
        computer.setDisk(disk);
        return this;
    }

    public Computer build() {
        return computer;
    }
}

public class Director {
    private ComputerBuilder computerBuilder;

    public Director(ComputerBuilder computerBuilder) {
        this.computerBuilder = computerBuilder;
    }

    public Computer construct() {
        return computerBuilder
                .setCpu("i5")
                .setMemory("8GB")
                .setDisk("1TB")
                .build();
    }
}

public class BuilderPatternDemo {
    public static void main(String[] args) {
        ComputerBuilder computerBuilder = new BasicComputerBuilder();
        Director director = new Director(computerBuilder);
        Computer computer = director.construct();

        System.out.println(computer.toString());
    }
}
  1. 原型模式(Prototype Pattern):
    原型模式透過複製現有物件來建立新對象,而不是重新建立。這可以提高物件的創建效率,尤其是當物件的初始化過程比較複雜時。以下是一個原型模式的程式碼範例:
public abstract class Shape implements Cloneable {
    private String id;
    protected String type;
    
    abstract void draw();

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    public Object clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

public class Circle extends Shape {
    public Circle() {
        type = "Circle";
    }

    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}

public class Rectangle extends Shape {
    public Rectangle() {
        type = "Rectangle";
    }

    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}

public class ShapeCache {
    private static Map<String, Shape> shapeMap = new HashMap<>();

    public static Shape getShape(String shapeId) {
        Shape cachedShape = shapeMap.get(shapeId);
        return (Shape) cachedShape.clone();
    }

    public static void loadCache() {
        Circle circle = new Circle();
        circle.setId("1");
        shapeMap.put(circle.getId(), circle);

        Rectangle rectangle = new Rectangle();
        rectangle.setId("2");
        shapeMap.put(rectangle.getId(), rectangle);
    }
}

public class PrototypePatternDemo {
    public static void main(String[] args) {
        ShapeCache.loadCache();

        Shape clonedShape1 = ShapeCache.getShape("1");
        System.out.println("Shape: " + clonedShape1.getType());

        Shape clonedShape2 = ShapeCache.getShape("2");
        System.out.println("Shape: " + clonedShape2.getType());
    }
}
  1. 適配器模式(Adapter Pattern):
    適配器模式將一個類別的介面轉換成客戶端所期望的另一個介面。這可以在不改變現有程式碼的情況下,為不相容的介面之間提供協同工作的能力。以下是一個適配器模式的程式碼範例:
public interface MediaPlayer {
    void play(String audioType, String fileName);
}

public interface AdvancedMediaPlayer {
    void playVlc(String fileName);

    void playMp4(String fileName);
}

public class VlcPlayer implements AdvancedMediaPlayer {
    public void playVlc(String fileName) {
        System.out.println("Playing vlc file. Name: " + fileName);
    }

    public void playMp4(String fileName) {
        // 空实现
    }
}

public class Mp4Player implements AdvancedMediaPlayer {
    public void playVlc(String fileName) {
        // 空实现
    }

    public void playMp4(String fileName) {
        System.out.println("Playing mp4 file. Name: " + fileName);
    }
}

public class MediaAdapter implements MediaPlayer {
    AdvancedMediaPlayer advancedMediaPlayer;

    public MediaAdapter(String audioType) {
        if (audioType.equalsIgnoreCase("vlc")) {
            advancedMediaPlayer = new VlcPlayer();
        } else if (audioType.equalsIgnoreCase("mp4")) {
            advancedMediaPlayer = new Mp4Player();
        }
    }

    public void play(String audioType, String fileName) {
        if (audioType.equalsIgnoreCase("vlc")) {
            advancedMediaPlayer.playVlc(fileName);
        } else if (audioType.equalsIgnoreCase("mp4")) {
            advancedMediaPlayer.playMp4(fileName);
        }
    }
}

public class AudioPlayer implements MediaPlayer {
    MediaAdapter mediaAdapter;

    public void play(String audioType, String fileName) {
        if (audioType.equalsIgnoreCase("mp3")) {
            System.out.println("Playing mp3 file. Name: " + fileName);
        } else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) {
            mediaAdapter = new MediaAdapter(audioType);
            mediaAdapter.play(audioType, fileName);
        } else {
            System.out.println("Invalid media. " + audioType + " format not supported");
        }
    }
}

public class AdapterPatternDemo {
    public static void main(String[] args) {
        AudioPlayer audioPlayer = new AudioPlayer();
        audioPlayer.play("mp3", "beyond_the_horizon.mp3");
        audioPlayer.play("mp4", "alone.mp4");
        audioPlayer.play("vlc", "far_far_away.vlc");
        audioPlayer.play("avi", "mind_me.avi");
    }
}
  1. 策略模式(Strategy Pattern):
    策略模式定義了一系列的演算法,並將每個演算法封裝起來,使得它們可以互相替換。這樣可以方便地切換演算法或擴展新的演算法,而不影響其他部分的程式碼。以下是一個策略模式的程式碼範例:
public interface Strategy {
    int doOperation(int num1, int num2);
}

public class OperationAdd implements Strategy {
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

public class OperationSubtract implements Strategy {
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

public class OperationMultiply implements Strategy {
    public int doOperation(int num1, int num2) {
        return num1 * num2;
    }
}

public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}

public class StrategyPatternDemo {
    public static void main(String[] args) {
        Context context = new Context(new OperationAdd());
        System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

        context = new Context(new OperationSubtract());
        System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

        context = new Context(new OperationMultiply());
        System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
    }
}

透過上述範例程式碼,我們對Java中常用的7種設計模式進行了簡單的介紹。每一種設計模式都有不同的場景和應用,它們可以在不同的專案中發揮作用。希望這篇文章可以幫助你了解並應用設計模式,並提升你的程式碼品質和開發效率。

以上是深入了解常用的7種Java設計模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn