“ 将抽象部分和实现部分分离,使他们都可以独立的变化。”
-《设计模式》GoF
个人理解:将一个事务进行多方面的抽象分离,利用组合实现绑定关系。
需求:游戏 坦克,多种型号、在不同平台上运行。
前提,有不同型号的坦克,具有相同的动作(射击,移动),但根据不同平台对于相同动作的实现是不同的,调用的API不同(PC和Mobile)。
这里有两个变化的方向:
1.多种型号的坦克(移动速度等不同)。
2.多种平台,实现不同(屏幕显示等不同)。
将第二个变化隔离出来,用组合的方式解决两者的耦合。
For different kinds of tank, we can use abstract class to solve it, some code like this
{
.......
public abstract void move();
public abstract void run();
.......
}
public abstract t01 : tank
{
........
public override void move()
{
........
// tank display : invoke some api to draw a tank on screen when it moves.
........
}
public override void shoot()
{
........
// tank display : invoke some api to draw a tank on screen when it shoots.
........
}
}
For different platform, we know the display of tank is different.Then should we do like this?
{
public override void move()
{
........
// invoke pc api to draw a tank on the pc screen.
........
}
.................................
}
public class MobileT01: tank
{
public override void move()
{
........
// invoke mobile api to draw a tank on the mobile screen.
........
}
.................................
}
Yeah, If we will get more requirements for different platform this will bring a hug work to our developer.
So we can design like this:
public abstract class tank
{
protected platform pf;
public tank(pf)
{
........
this .pf = pf;
........
}
public abstract void move();
public abstract void shoot();
........
}
public class T01
{
public T01(platform pf): base (pf)
{
........
}
public override move()
{
........
pf.display();
........
}
............
}
public abstract class platform
{
.......
public abstract void display();
.......
}
public class pcplatform : platform
{
public override void display()
{
// invoke pc api to draw tank.
}
}
public class mobileplatform : platform
{
public override void display()
{
// invoke mobile api to draw tank.
}
}
Then we can according the plat we use to dicide which platform we should create or new.
Any more requirement for running on different platform, we just need add an abstract class to the system.and create the suitable platform instance.