JAVA使用MVC体系结构写一个包含三种设计模式
时间: 2023-07-20 09:11:49 浏览: 102
好的,我可以给您提供一个示例,展示如何使用MVC体系结构并结合三种设计模式(工厂模式、观察者模式和装饰器模式)。
首先,我们定义一个模型接口:
```java
public interface Model {
void doSomething();
}
```
然后,我们实现两个模型类:
```java
public class ModelImplA implements Model {
@Override
public void doSomething() {
System.out.println("Model A is doing something.");
}
}
public class ModelImplB implements Model {
@Override
public void doSomething() {
System.out.println("Model B is doing something.");
}
}
```
接下来,我们定义一个工厂类,用于创建模型实例:
```java
public class ModelFactory {
public static Model createModel(String type) {
switch (type) {
case "A":
return new ModelImplA();
case "B":
return new ModelImplB();
default:
throw new IllegalArgumentException("Unknown model type: " + type);
}
}
}
```
现在,我们可以在控制器中使用工厂类来创建模型实例:
```java
public class Controller {
private Model model;
public Controller(String modelType) {
this.model = ModelFactory.createModel(modelType);
}
public void doSomething() {
model.doSomething();
}
}
```
接下来,我们定义一个观察者接口:
```java
public interface Observer {
void update();
}
```
然后,我们定义一个主题类,用于管理观察者:
```java
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
```
现在,我们可以在模型中使用主题类来通知观察者:
```java
public class ModelImplA implements Model {
private Subject subject = new Subject();
@Override
public void doSomething() {
System.out.println("Model A is doing something.");
subject.notifyObservers();
}
public void addObserver(Observer observer) {
subject.addObserver(observer);
}
public void removeObserver(Observer observer) {
subject.removeObserver(observer);
}
}
```
接下来,我们定义一个装饰器类,用于对模型进行装饰:
```java
public class ModelDecorator implements Model {
private Model model;
private List<Observer> observers = new ArrayList<>();
public ModelDecorator(Model model) {
this.model = model;
if (model instanceof ModelImplA) {
((ModelImplA) model).addObserver(() -> notifyObservers());
}
}
@Override
public void doSomething() {
model.doSomething();
}
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
private void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
```
最后,我们定义一个视图类:
```java
public class View {
private Controller controller;
public View(String modelType) {
this.controller = new Controller(modelType);
}
public void doSomething() {
controller.doSomething();
}
}
```
现在,我们可以在主函数中使用这些类来运行我们的程序:
```java
public class Main {
public static void main(String[] args) {
View view = new View("A");
ModelDecorator modelDecorator = new ModelDecorator(ModelFactory.createModel("A"));
view.doSomething();
modelDecorator.doSomething();
}
}
```
这样,我们就使用了工厂模式、观察者模式和装饰器模式,并使用MVC体系结构组织了我们的代码。
阅读全文