定义:定义一个统一的接口,用来访问子系统中的一群接口。外观定义了一个高层接口,让子系统更容易使用。
UML类图:
C++实现:
#include<iostream>
using namespace std;
class Shape
{
virtual void Draw() = 0;
public:
virtual ~Shape() = default;
};
class Circle :public Shape
{
public:
// 通过 Shape 继承
virtual void Draw() override
{
cout << "Draw Circle!" << endl;
}
virtual ~Circle() {}
};
class Sphere :public Shape
{
public:
// 通过 Shape 继承
virtual void Draw() override
{
cout << "Draw Sphere!" << endl;
}
virtual ~Sphere() {}
};
class Cube :public Shape
{
public:
// 通过 Shape 继承
virtual void Draw() override
{
cout << "Draw Cube!" << endl;
}
virtual ~Cube() {}
};
class Context
{
Circle* circle;
Sphere* sphere;
Cube* cube;
public:
Context()
{
circle = new Circle();
sphere = new Sphere();
cube = new Cube();
}
void DrawCircle()
{
circle->Draw();
}
void DrawSphere()
{
sphere->Draw();
}
void DrawCube()
{
cube->Draw();
}
~Context()
{
delete circle;
delete sphere;
delete cube;
}
};
int main()
{
Context* context = new Context();
context->DrawCircle();
context->DrawSphere();
context->DrawCube();
delete context;
return 0;
}
C#实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using static System.Console;
namespace ConsoleApp1
{
public interface Shape
{
void Draw();
}
public class Circle:Shape
{
public void Draw()
{
WriteLine("Draw Circle!");
}
}
public class Sphere : Shape
{
public void Draw()
{
WriteLine("Draw Sphere!");
}
}
public class Cube : Shape
{
public void Draw()
{
WriteLine("Draw Cube!");
}
}
public class Context
{
private Circle circle;
private Sphere sphere;
private Cube cube;
public Context()
{
circle = new Circle();
sphere = new Sphere();
cube = new Cube();
}
public void DrawCircle()
{
circle.Draw();
}
public void DrawSphere()
{
sphere.Draw();
}
public void DrawCube()
{
cube.Draw();
}
}
class Program
{
static void Main(string[] args)
{
Context context = new Context();
context.DrawCircle();
context.DrawCube();
context.DrawSphere();
}
}
}