桥模式

经典的就是坦克例子

比如定义一个坦克,有各种型号,T50.T69,T99等,电脑上游戏的坦克有一种,手机上坦克有一种

经典代码,我直接贴代码

 public abstract class Tank

    {

        protected TankPlatformImplementation tankImpl;



        public Tank(TankPlatformImplementation tankImpl)

        {

            this.tankImpl = tankImpl;

        }



        public abstract void Shot();

        public abstract void Run();

        public abstract void Stop();

    }
 public abstract class TankPlatformImplementation

    {

        public abstract void MoveTankTo();

        public abstract void DrawTank();

        public abstract void DoShot();

        public abstract void Stop();

    }
 public class T50:Tank

    {

        public T50( TankPlatformImplementation tankImpl )

            : base( tankImpl )

        {

        }



        public override void Shot()

        {

            tankImpl.DoShot();

        }



        public override void Run()

        {

            tankImpl.MoveTankTo();

        }



        public override void Stop()

        {

            tankImpl.Stop();

        }

    }



    public class T75 : Tank

    {

        public T75( TankPlatformImplementation tankImpl )

            : base( tankImpl )

        {

        }



        public override void Shot()

        {

            tankImpl.DoShot();

        }



        public override void Run()

        {

            tankImpl.MoveTankTo();

        }



        public override void Stop()

        {

            tankImpl.Stop();

        }

    }
public class PCTankImplementation:TankPlatformImplementation

    {

        public override void MoveTankTo()

        {

        }



        public override void DrawTank()

        {

        }



        public override void DoShot()

        {

        }



        public override void Stop()

        {

        }

    }



    public class MobileankImplementation : TankPlatformImplementation

    {

        public override void MoveTankTo()

        {

        }



        public override void DrawTank()

        {

        }



        public override void DoShot()

        {

        }



        public override void Stop()

        {

        }

    }

调用

class Program

    {

        static void Main( string[] args )

        {

            TankPlatformImplementation tankImpl = new PCTankImplementation();



            Tank tank = new T50( tankImpl );

        }

    }

这样子达到松耦合,客户端可以实现灵活多变,也拒绝了繁琐急剧膨胀的类型继承,达到结构明晰

你可能感兴趣的:(模式)