外观模式

外观模式

定义

外观模式,又称门面模式,它提供了一个统一的接口,用来访问子系统中的一群接口。外观定义了一个高层接口,让子系统更容易使用。

架构示意图:

意图:

提供一个简单接口,让子系统更易于使用。

最少知识原则:

Least Knowledge:只和你的密友交谈。

这个原则希望我们在设计中,不要让太多的类耦合在一起,免得修改系统中一部分,会影响到其他部分。如果许多类之间相互依赖,那么这个系统就会变成一个易碎的系统,它需要花许多成本维护,也会因为太复杂而不容易被其他人了解。

要点:

1. 当需要简化并统一一个很大的接口或者一群复杂的接口时,使用外观。

2. 外观将客户从一个复杂的子系统中解耦。

3. 实现一个外观,需要将子系统组合进外观中,然后将工作委托给子系统执行。

实例

子系统:

Gas :子系统——天然气对象

public class Gas {

    public void open() {

        System.out.println("open the gas!");

    }

    public void close() {

         System.out.println("close the gas!");

     }

}

Oil :子系统——油对象

public class Oil {

    public void put() {

        System.out.println("put the oil");

    }

}

Pot :子系统——锅对象

public class Pot {

    public void cook() {

        System.out.println("cook!");

    }

    public void finished() {

        System.out.println("finished");

    }

}

Vegetables :子系统——蔬菜类

public class Vegetables {

    public void put() {

        System.out.println("put the vegetalbes!");

    }

}

Facade :门面对象

public class Facade {

    public void cook() {

        Gas gas = new Gas();

        Oil oil = new Oil();

        Vegetables vegetables = new Vegetables();

        Pot pot = new Pot();

        gas.open();

        oil.put();

        vegetables.put();

        pot.cook();

        pot.finished();

        gas.close();

    }

}

Client :客户端

public class Client {

    public static void main(String args[]) {   

        //1.旧的方法,客户端需要知道很多子系统对象

        Client client = new Client();

        client.method1();

        //2.门面模式,解耦,客户端只需要知道门面对象即可

        Facade facade = new Facade();

        facade.cook();    

    }

    /**

     * 旧的客户端方法

     */

    public void method1() {

        Gas gas = new Gas();

        Oil oil = new Oil();

        Vegetables vegetables = new Vegetables();

        Pot pot = new Pot();

        gas.open();

        oil.put();

        vegetables.put();

        pot.cook();

        pot.finished();

        gas.close();

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值