Java設計模式是指在軟件設計中經常使用的一些解決方案,它們可以幫助我們更好地組織代碼,提高代碼的復用性和可維護性。
下面我們介紹幾種常見的Java設計模式:
// 單例模式 public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } // 工廠模式 public interface Shape { void draw(); } public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } 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; } } // 觀察者模式 public interface Observer { void update(String message); } public class Subscriber implements Observer { private String name; public Subscriber(String name) { this.name = name; } @Override public void update(String message) { System.out.println(name + " received message: " + message); } } public interface Subject { void attach(Observer observer); void detach(Observer observer); void notify(String message); } public class Publisher implements Subject { private Listobservers = new ArrayList<>(); @Override public void attach(Observer observer) { observers.add(observer); } @Override public void detach(Observer observer) { observers.remove(observer); } @Override public void notify(String message) { for (Observer o : observers) { o.update(message); } } }
這些設計模式在實際開發中都有著廣泛的應用,可以幫助我們更好地解決各種問題,提高開發效率。