实验目的
(1) 理解设计模式的基本概念; (2) 理解设计模式遵循的原则;
(3) 掌握经典设计模式及应用。
实验内容
一、能播放各种声音的软件产品(理解开-闭原则(Open-Closed Principle,OCP–对扩展开放-而对修改关闭)。写java文件、编译java文件、执行class文件。
- Application
public class Application {
public static void main(String[] args) {
Simulator simulator = new Simulator();
simulator.setSound(new Dog());
simulator.play();
simulator.setSound(new Violin());
simulator.play();
}
}
- Simulator
public class Simulator {
Sound sound;
public void setSound(Sound sound) {
this.sound=sound;
}
public void play() {
if(sound!=null) {
sound.playSound();
} else {
System.out.println("没有可播放的声音");
}
}
}
- ** Sound**
public interface Sound {
public abstract void playSound();
}
- Dog
public class Dog implements Sound {
public void playSound() {
System.out.println("汪汪...汪汪");
}
}
- violin
public class Violin implements Sound {
public void playSound() {
System.out.println("小提琴.梁祝");
}
}
二、简单工厂模式–女娲造人。写java文件、编译java文件、执行class文件。
女娲架起了八卦炉(技术术语:建立工厂),开始造人。
过程如下:先捏泥巴成人形,再放入八卦炉里烤,最后扔到地上成长。时间烤短了,造出了“白种人”;时间烤长了,造出了“黑种人”;时间烤得不长不短,造出了“黄种人”。
- Human
public interface Human {
public void talk();
}
- HumanFactory
public class HumanFactory {
public static Human createHuman(String s) {
Human human=null;
if(s.equals(new String("whiteHuman")))
human=new WhiteHuman();
if(s.equals(new String("yellowHuman")))
human=new YellowHuman();
return human;
}
}
- BlackHuman
public class BlackHuman implements Human {
public void talk() {
System.out.println("黑人");
}
}
- WhiteHuman
public class WhiteHuman implements Human {
public void talk() {
System.out.println("Hello!");
}
}
- YellowHuman
public class YellowHuman implements Human {
public void talk() {
System.out.println("您好!");
}
}
- NvWa
public class NvWa {
public static void main(String [] args) {
Human human=HumanFactory.createHuman("yellowHuman");
human.talk();
}
}
三、工厂方法模式–女娲造人。写java文件、编译java文件、执行class文件。
- Human
public interface Human {
public void talk();
}
- HumanFactory
public interface HumanFactory {
public Human createHuman