------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
1.代理设计
package com.itheima.zqt;
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() ; // 客户只关心上网浏览一个操作
}
};
真实主题完成的只是上网的基本功能,而代理主题要做比真实主题更多的业务相关的操作。
多线程中Thread和Runnable接口就是代理设计模式
工厂设计模式
如果需要添加子类,直接修改工厂类就而无需改变main函数。
package com.itheima.zqt;
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() ;
}
}
};