抽象类与接口的应用(二)
ceCaseDemo02{
public static void main(String args[]){
Computer.plugin(new Flash()) ;
Computer.plugin(new Print()) ;
}
};
4、工厂设计模式
[java]
interface Fruit{ // 定义一个水果接口
public void eat() ; // 吃水果
}
class Apple implements Fruit{
public void eat(){
System.out.println("** 吃苹果。") ;
}
};
class Orange implements Fruit{
public void eat(){
System.out.println("** 吃橘子。") ;
}
};
public class InterfaceCaseDemo03{
public static void main(String args[]){
Fruit f = new Apple() ; // 实例化接口
f.eat() ;
}
};
此过渡端在程序中就称为工厂设计。
[java]
interface Fruit{ // 定义一个水果接口
public void eat() ; // 吃水果
}
class Apple implements Fruit{
public void eat(){
System.out.println("** 吃苹果。") ;
}
};
class Orange implements Fruit{
public void eat(){
System.out.println("** 吃橘子。") ;
}
};
class Factory{ // 定义工厂类
public static Fruit getInstance(String className){
Fruit f = null ;
if("apple".equals(className)){ // 判断是否要的是苹果的子类
f = new Apple() ;
}
if("orange".equals(className)){ // 判断是否要的是橘子的子类
f = new Orange() ;
}
return f ;
}
};
public class InterfaceCaseDemo05{
public static void main(String args[]){
Fruit f = Factory.getInstance(args[0]) ; // 实例化接口
if(f!=null){ // 判断是否取得实例
f.eat() ;
}
}
};
5、代理设计模式
[java]
interface Network{
public void browse() ; // 浏览
}
class Real implements Network{
public void browse(){
System.out.println("上网浏览信息") ;
}
};
class Proxy implements Network{
private Network network ; // 代理对象
public Proxy(Network network){
this.network = network ;
}
public void check(){
System.out.println("检查用户是否合法。") ;
}
public void browse(){
this.check() ;
this.network.browse() ; // 调用真实的主题操作
}
};
public class ProxyDemo{
public static void main(String args[]){
Network net = null ;
net = new Proxy(new Real()) ;// 指定代理操作
net.browse() ; // 客户只关心上网浏览一个操作
}
};
6、适配器设计
[java]
interface Window{ // 定义Window接口,表示窗口操作
public void open() ; // 打开
public void close() ; // 关闭
public void activated() ; // 窗口活动
public void iconified() ; // 窗口最小化
public void deiconified();// 窗口恢复大小
}
abstract class WindowAdapter implements Window{
public void open(){} ; // 打开
public void close(){} ; // 关闭
public void activated(){} ; // 窗口活动
public void iconified(){} ; // 窗口最小化
public void deiconified(){};// 窗口恢复大小
};
class WindowImpl extends WindowAdapter{
public void open(){
System.out.println("窗口打开。") ;
}
public void close(){
System.out.println("窗口关闭。") ;
}
};
public class AdapterDemo{
public static void main(String args[]){
Window win = new WindowImpl() ;
win.open() ;
win.close() ;
}
};
7、内部类的扩展
抽象类中包含一个接口
[java]
abstract class A{ // 定义抽象类
public abstract void printA() ; // 抽象方法
interface B{ // 定义内部接口
publi