运用三种设计模式的程序
时间: 2023-07-25 19:18:35 浏览: 108
C++二十三种设计模式
以下是一个运用了三种设计模式的程序示例:
```java
// 工厂模式
public interface Animal {
void makeSound();
}
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("汪汪汪!");
}
}
public class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("喵喵喵!");
}
}
public class AnimalFactory {
public Animal createAnimal(String type) {
if (type.equalsIgnoreCase("dog")) {
return new Dog();
} else if (type.equalsIgnoreCase("cat")) {
return new Cat();
} else {
return null;
}
}
}
// 装饰器模式
public interface Component {
void operation();
}
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("执行具体组件的操作");
}
}
public class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("为具体组件增加额外的操作");
}
}
// 观察者模式
public interface Observer {
void update(String message);
}
public interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notify(String message);
}
public class ConcreteSubject implements Subject {
private List<Observer> observers = 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 observer : observers) {
observer.update(message);
}
}
}
public class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + "收到消息:" + message);
}
}
public class ObserverTest {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
Observer observer1 = new ConcreteObserver("张三");
Observer observer2 = new ConcreteObserver("李四");
subject.attach(observer1);
subject.attach(observer2);
subject.notify("新商品已上架");
}
}
```
这个程序示例中,工厂模式用于创建不同种类的动物对象,装饰器模式用于给已有的组件增加额外的操作,观察者模式用于实现对象之间的消息通知。
阅读全文