在Java中,內部類是指在一個類中定義的另一個類。內部類可以分為四種類型:成員內部類、局部內部類、匿名內部類和靜態內部類。內部類的設計模式實踐可以使代碼更加靈活、模塊化和可維護。
以下是一些常見的設計模式實踐與內部類的結合:
public class FactoryExample {
public interface Product {
void display();
}
public static class ConcreteProduct implements Product {
@Override
public void display() {
System.out.println("Displaying ConcreteProduct");
}
}
public static class ProductFactory {
public Product createProduct() {
return new ConcreteProduct();
}
}
public static void main(String[] args) {
ProductFactory factory = new ProductFactory();
Product product = factory.createProduct();
product.display();
}
}
import java.util.ArrayList;
import java.util.List;
public class ObserverPatternExample {
public interface Observer {
void update(String message);
}
public static class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
public static class ConcreteObserver implements Observer {
@Override
public void update(String message) {
System.out.println("Received message: " + message);
}
}
public static void main(String[] args) {
Subject subject = new Subject();
Observer observer = new ConcreteObserver();
subject.addObserver(observer);
subject.notifyObservers("Hello, World!");
}
}
public class SingletonPatternExample {
private SingletonPatternExample() {}
private static class SingletonHolder {
private static final SingletonPatternExample INSTANCE = new SingletonPatternExample();
}
public static SingletonPatternExample getInstance() {
return SingletonHolder.INSTANCE;
}
public void display() {
System.out.println("Displaying SingletonPatternExample");
}
public static void main(String[] args) {
SingletonPatternExample instance1 = SingletonPatternExample.getInstance();
instance1.display();
SingletonPatternExample instance2 = SingletonPatternExample.getInstance();
instance2.display();
System.out.println(instance1 == instance2); // true
}
}
總的來說,內部類與設計模式的結合可以幫助我們編寫出更加模塊化、靈活和可維護的代碼。在實際項目中,根據具體的需求和場景選擇合適的設計模式與內部類結合,可以提高代碼的質量和效率。