此类图中包含了几个动物类,Tiger、Dog和Cat,它们都包含各自的功能,三个类互相协作,以便完成类似于动物世界的游戏功能。因每个类都保持有其他两个类的类型的私有变量,在这个设计中的三个动物类之间存在高度的耦合。请在基本功能不变的情况下,对以上的设计选用合适的模式进行重构。 采用中介者模式使用java实现代码
时间: 2023-06-16 22:02:58 浏览: 289
以下是采用中介者模式进行重构的Java代码实现:
```java
public interface AnimalMediator {
void play();
void feed(String animalType);
void sleep(String animalType);
}
public class AnimalGame implements AnimalMediator {
private Tiger tiger;
private Dog dog;
private Cat cat;
public AnimalGame(Tiger tiger, Dog dog, Cat cat) {
this.tiger = tiger;
this.dog = dog;
this.cat = cat;
}
@Override
public void play() {
System.out.println("开始玩耍!");
tiger.roar();
dog.bark();
cat.meow();
}
@Override
public void feed(String animalType) {
System.out.println("给" + animalType + "喂食!");
switch (animalType) {
case "Tiger":
tiger.eat();
break;
case "Dog":
dog.eat();
break;
case "Cat":
cat.eat();
break;
default:
System.out.println("无法识别的动物类型!");
}
}
@Override
public void sleep(String animalType) {
System.out.println(animalType + "开始睡觉!");
switch (animalType) {
case "Tiger":
tiger.rest();
break;
case "Dog":
dog.rest();
break;
case "Cat":
cat.rest();
break;
default:
System.out.println("无法识别的动物类型!");
}
}
}
public abstract class Animal {
protected AnimalMediator mediator;
protected String type;
public Animal(String type, AnimalMediator mediator) {
this.type = type;
this.mediator = mediator;
}
public abstract void eat();
public abstract void rest();
}
public class Tiger extends Animal {
public Tiger(AnimalMediator mediator) {
super("Tiger", mediator);
}
public void roar() {
System.out.println("老虎咆哮!");
}
@Override
public void eat() {
System.out.println("老虎吃肉!");
}
@Override
public void rest() {
System.out.println("老虎躺下休息!");
}
}
public class Dog extends Animal {
public Dog(AnimalMediator mediator) {
super("Dog", mediator);
}
public void bark() {
System.out.println("狗叫汪汪!");
}
@Override
public void eat() {
System.out.println("狗啃骨头!");
}
@Override
public void rest() {
System.out.println("狗趴下休息!");
}
}
public class Cat extends Animal {
public Cat(AnimalMediator mediator) {
super("Cat", mediator);
}
public void meow() {
System.out.println("猫叫喵喵!");
}
@Override
public void eat() {
System.out.println("猫吃鱼!");
}
@Override
public void rest() {
System.out.println("猫卧下休息!");
}
}
public class Main {
public static void main(String[] args) {
Tiger tiger = new Tiger(new AnimalGame(tiger, dog, cat));
Dog dog = new Dog(new AnimalGame(tiger, dog, cat));
Cat cat = new Cat(new AnimalGame(tiger, dog, cat));
AnimalMediator mediator = new AnimalGame(tiger, dog, cat);
mediator.play();
mediator.feed("Tiger");
mediator.feed("Dog");
mediator.feed("Cat");
mediator.sleep("Tiger");
mediator.sleep("Dog");
mediator.sleep("Cat");
}
}
```
在这个重构后的设计中,中介者模式被用于减少三个动物类之间的耦合。在这种模式下,AnimalMediator 接口充当中介者角色,AnimalGame 类实现了中介者接口。每个动物类都持有中介者的引用,并通过中介者来与其他动物类进行通信。当需要进行玩耍、喂食或休息时,动物类会向中介者发送请求,中介者会根据请求类型来调用相应的方法。这样,每个动物类都可以专注于自己的功能,而不需要关心其他动物类的状态和行为。
阅读全文