展示接口实现“功能扩展”
【需求】主板预留PCI插槽。不可能知道该插槽将插装什么硬件。
主板做的事情只能是:加电、启动、run、停止。
主板类预留5个PCI插槽,如何实现?
interface PCI{ //PCI插槽应遵循的标准
void start();
void run();
void stop();
}
class NetCard implements PCI{
public void start() {System.out.print("\n网卡启动");}
public void run() {System.out.print(" 网卡运行");}
public void stop() {System.out.print("\n网卡停止");}
}
class SoundCard implements PCI{
public void start() {System.out.print("\n声卡启动");}
public void run() {System.out.print(" 声卡运行");}
public void stop() {System.out.print("\n声卡停止");}
}
class DisplayCard implements PCI{
public void start() {System.out.print("\n显卡启动");}
public void run() {System.out.print(" 显卡运行");}
public void stop() {System.out.print("\n显卡停止");}
}
class MainBoard{ //主板
PCI [] p = new PCI [5]; //创建的不是PCI对象(实际没有PCI对象),因为接口不是类,没有构造函数
public void add(PCI x) {
for(int i=0;i<p.length;i++)
if(p[i] == null) {
p[i]=x; return;
}
System.out.print("已插满,无法插入!");
}
public void start() { //模拟主板加电运行
for(int i=0;i<p.length;i++) {
if(p[i]!=null) {
p[i].start();
p[i].run();
}
}
}
public void stop() { //模拟主板关机前的停止
for(int i=0;i<p.length;i++)
if(p[i]!=null)
p[i].stop();
}
}
class Computer{
MainBoard m = new MainBoard(); //电脑中有一块主板
public Computer(PCI [] p) { //电脑中插装何种板卡未知,通过参数传入
for(int i=0;i<p.length;i++)
m.add(p[i]);
}
public void start() { m.start();}
public void stop() { m.stop();}
}
class App_PCI{
public static void main(String [] args) {
PCI[] a = { new NetCard(),new SoundCard(),new DisplayCard()};
Computer c = new Computer(a);
c.start();
c.stop();
}
}
//注:
PCI [] p = new PCI [5]; 创建的不是PCI对象(实际没有PCI对象),因为接口不是类,没有构造函数