当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 设计模式系列 - 外观模式

设计模式系列 - 外观模式

2018年12月25日  | 移动技术网IT编程  | 我要评论

外观模式通过创建新的对象访问接口,从而隐藏对象内部发复复杂性

介绍

外观模式属于结构型模式,通过定义的外观器,从而简化了具体对象的内部复杂性。这种模式通过在复杂系统和上层调用之间添加了一层,这一层对上提供简单接口,对下执行复杂操作。

类图描述

通过上图我们可以发现,ishape 为行为接口,然后 rectangle square circle 为具体的对象实体类型, shapemarker 为我们定义的外观器,通过它,我们能间接访问复杂对象。

代码实现

1、定义对象接口

public interface ishape
{
    void draw();
}

2、定义实体对象类型

public class circle:ishape
{
    public void draw() => console.writeline("circle:draw()");
}
public class rectangle:ishape
{
    public void draw() => console.writeline("rectangle:draw()");
}
public class square:ishape
{
    public void draw() => console.writeline("square:draw()");
}

3、定义外观类

public class shapemarker
{
    private ishape circle;
    private ishape rectangle;
    private ishape square;

    public shapemarker()
    {
        circle = new circle();
        rectangle = new rectangle();
        square = new square();
    }

    public void drawcircle() => circle.draw();
    public void drawrectangle() => rectangle.draw();
    public void drawsquare() => square.draw();
}

4、上层调用

class program
{
    static void main(string[] args)
    {
        var shapemarker = new shapemarker();
        shapemarker.drawcircle();
        shapemarker.drawrectangle();
        shapemarker.drawsquare();
        console.readkey();
    }
}

总结

外观模式不符合开闭原则,如果外观类执行的操作过于复杂的话,则不建议使用这种模式。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网