您的位置:首页 > 其它

接口实际应用——工厂设计模式(Factory)和代理设计模式(Proxy)

2018-03-17 23:47 585 查看
工厂设计模式(Factory)
工厂设计模式是Java开发中使用最多的一种设计模式
interface Fruit{
public void eat();	//接口只能有抽象方法,所以abstract可以省略
}
class Apple implements Fruit{
public void eat(){
System.out.println("吃苹果。");
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("吃橘子。");
}
}
public class Main {
public static void main(String[] args) {
Fruit f = new Apple();	//实例化接口对象
f.eat();
}
}
运行结果:吃苹果    对于程序来说主方法(或主类的一个客户端),客户端的操作越简单越好,但是本程序的问题是,客户端中,一个接口和一个固定的子类绑在一起了(Fruit f = new Apple();)    本程序最大的问题是耦合,在主方法中一个接口和一个子类紧密耦合在一起,这种方法可以简单理解成“A→B模式”,为了便于维护,需要在中间加入一个过渡使其变成“A→C→B模式”,这样B、C的改变不会影响到A实现程序的可移植性。

改变程序:
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){
if("apple".equals(className)){
return new Apple();
}
if("Orange".equals(className)){
return new Orange();
}
return null;
}
}
public class Main {
public static void main(String[] args) {
Fruit f = Factory.getInstance("apple");
f.eat();
}
}
    此时,客户端不在和一个具体的子类耦合,计算增加新的子类,也只需要修改Factory类即可。

代理设计模式(Proxy)
    代理设计模式,就是指一个代理主题来操作真实主题。真实主题执行具体的业务操作,而代理主题负责其他相关业务的处理。(类似于代理上网,客户通过网络代理连接网络)
interface Network{ //定义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 Main{
public static void main(String args[]){
Network net = null;
net = new Proxy(new Real());
net.browse();
}
}真实主题实现类(Real)完成的只是上网的最基本功能,而代理主题(Proxy)要做的比真实主题更多的相关业务操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: