Interfaces:
public interface ICar
{
int Fuel{get;set;}
void Run();
}
public interface IPlane
{
int Fuel{get;set;}
void Fly();
}
{
int Fuel{get;set;}
void Run();
}
public interface IPlane
{
int Fuel{get;set;}
void Fly();
}
Base classes:
public class abstract CarBase : ICar
{
private int mFuel = 0;
public virtual int Fuel
{
get{ return mFuel; }
set{ mFuel = value; }
}
public virtual void Run()
{
Fuel--;
Console.WriteLine( "Run, Fuel = {0}", Fuel );
}
}
public class abstract PlaneBase : IPlane
{
private int mFuel = 0;
public virtual int Fuel
{
get{ return mFuel; }
set{ mFuel = value; }
}
public virtual void Fly()
{
Fuel-=2;
Console.WriteLine( "Fly , Fuel = {0}", Fuel );
}
}
{
private int mFuel = 0;
public virtual int Fuel
{
get{ return mFuel; }
set{ mFuel = value; }
}
public virtual void Run()
{
Fuel--;
Console.WriteLine( "Run, Fuel = {0}", Fuel );
}
}
public class abstract PlaneBase : IPlane
{
private int mFuel = 0;
public virtual int Fuel
{
get{ return mFuel; }
set{ mFuel = value; }
}
public virtual void Fly()
{
Fuel-=2;
Console.WriteLine( "Fly , Fuel = {0}", Fuel );
}
}
我们要造一辆同时具有Car和Plane的车, 但使用同一个油箱.
public partial class FlayableCar
{
ICar mCar;
IPlane mPlane;
int mFuel = 1000;
public ICar Car
{
if(mCar==null) mCar = new NestedCar(this);
return mCar;
}
public IPlane Plane
{
if(mPlane==null) mPlane = new NestedPlane(this);
return mCar;
}
}
public partial class FlayableCar
{
private class NestedCar : CarBase
{
FlayableCar mOuter;
public class NestedCar(FlayableCar outer)
{
this.mOuter = outer;
}
public override int Fuel
{
get
{
return mOuter.mFuel;
}
set
{
mOuter.mFuel = value
}
}
}
}
public partial class FlayableCar
{
private class NestedPlane : PlaneBase
{
FlayableCar mOuter;
public class NestedPlane(FlayableCar outer)
{
this.mOuter = outer;
}
public override int Fuel
{
get
{
return mOuter.mFuel;
}
set
{
mOuter.mFuel = value
}
}
}
}
{
ICar mCar;
IPlane mPlane;
int mFuel = 1000;
public ICar Car
{
if(mCar==null) mCar = new NestedCar(this);
return mCar;
}
public IPlane Plane
{
if(mPlane==null) mPlane = new NestedPlane(this);
return mCar;
}
}
public partial class FlayableCar
{
private class NestedCar : CarBase
{
FlayableCar mOuter;
public class NestedCar(FlayableCar outer)
{
this.mOuter = outer;
}
public override int Fuel
{
get
{
return mOuter.mFuel;
}
set
{
mOuter.mFuel = value
}
}
}
}
public partial class FlayableCar
{
private class NestedPlane : PlaneBase
{
FlayableCar mOuter;
public class NestedPlane(FlayableCar outer)
{
this.mOuter = outer;
}
public override int Fuel
{
get
{
return mOuter.mFuel;
}
set
{
mOuter.mFuel = value
}
}
}
}
使用
FlyableCar flyableCar = new FlyableCar();
ICar car = flyableCar.Car;
car.Run();
IPlane plane = flyableCar.Plane;
plane.Fly();
ICar car = flyableCar.Car;
car.Run();
IPlane plane = flyableCar.Plane;
plane.Fly();