我也谈设计模式(外观模式)

外观模式概念

  1. 外观模式属于结构模式,隐藏系统的复杂性。
  2. 为客户端提供了一个接口来使用客户端访问系统。
  3. 提供一个类,它提供客户端所需的简化方法,并将调用委托给现有系统类的方法。

外观模式Demo说明

  1. 创建一个IShape接口和实现IShape接口的具体类
  2. 创建一个门面类ShapeMaker,它使用具体类将用户调用委托给这些类

UML图

外观模式设计图

步骤

1. 创建一个接口

public interface IShape
{
	void Draw();
}

2. 创建实现相同接口的具体类

public class Rectangle : IShape
{
	public void Draw()
	{
		//画三角形
		//Debug.WriteLine("Rectangle: Draw");
	}
}

public class Square : IShape
{
	public void Draw()
	{
		//画方形
		//Debug.WriteLine("Square: Draw");
	}
}

public class Circle IShape
{
	public void Draw()
	{
		//画圆形
		//Debug.WriteLine("Circle: Draw");
	}
}

3. 创建一个门面类

public cla 大专栏  我也谈设计模式(外观模式)ss ShapeMaker
{
	private IShape m_circle;
	private IShape m_rectangle;
	private IShape m_square;

	public ShapeMaker()
	{
		m_circle = new Circle();
		m_rectangle = new Rectangle();
		m_square = new Square();
	}

	public void DrawCircle()
	{
		m_circle.Draw();
	}
	public void DrawRectangle()
	{
		m_rectangle.Draw();
	}
	public void DrawSquare()
	{
		m_square.Draw();
	}
}

4. 使用外观类画各种形状

public class FacadePatternDemo
{
	public static void Main(string[] args)
	{
		var shapeMaker =  new ShapeMaker();

		shapeMaker.DrawCircle();
		shapeMaker.DrawRectangle();
		shapeMaker.DrawSquare();
	}
}

猜你喜欢

转载自www.cnblogs.com/wangziqiang123/p/11711149.html