Java 接口的应用:PCI

展示接口实现“功能扩展”
【需求】主板预留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对象),因为接口不是类,没有构造函数

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值