设计模式之外观模式的学习思考

外观模式属于设计模式里的结构型模式的一种,核心思想是隐藏系统的复杂性,并向客户端 提供了可以访问的接口。

个人认为外观模式是其他设计模式的基础,在许多模式里都有体现。较易掌握。

思路:

  1. 设计一个接口和分别实现接口的类(系统类)
  2. 设计一个类(实现类),类的数据成员是系统类对象,private控制权限,封装
  3. 类的的方法分别调用数据成员对象的方法
  4. 最后public类main方法调用展现

设计:

  1. 一个接口Shape,和实现接口类Circle、Rectangle、Square,各类重写接口里的抽象方法
  2. 一个实现类,ShapeMaker把接口实现类的各个对象封装,方法调用

代码:

interface Shape{
    void draw();
}

class Rectangle implements Shape{

    public void draw() {
        System.out.println("Rectangle:draw()");

    }

}

class Square implements Shape{

    public void draw() {
        System.out.println("Square:draw()");

    }

}

class Circle implements Shape{

    public void draw() {
        System.out.println("Circle:draw()");

    }

}
class ShapeMaker{
    private Shape circle;
    private Shape rectangle;
    private Shape square;       //封装系统内部复杂性,提供外部接口调用
    ShapeMaker(){
        circle=new Circle();
        rectangle=new Rectangle();
        square=new Square();
    }

    public void drawCircle(){
        circle.draw();
    }
    public void drawRecrangle(){
        rectangle.draw();
    }
    public void drawSquare(){
        square.draw();
    }
}
public class FacadePatternDemo {
    public static void main(String[] args) {
        ShapeMaker shapeMaker=new ShapeMaker();
        shapeMaker.drawCircle();
        shapeMaker.drawRecrangle();
        shapeMaker.drawSquare();
    }
}

输出:

Circle:draw()
Rectangle:draw()
Square:draw()

总结:

  • 简单易用
  • 是面向接口编程和组合编程的思想体现
  • 但是改变麻烦
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值