在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
}
}
总的来说,内部类与设计模式的结合可以帮助我们编写出更加模块化、灵活和可维护的代码。在实际项目中,根据具体的需求和场景选择合适的设计模式与内部类结合,可以提高代码的质量和效率。