标签:
当一个类有两个维度的变化时,我们就可以用组合替代继承,那么就可以避免继承带来的重复代码书写。
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { public abstract class Color { public string col; } public class RedColor : Color { public RedColor() { col = "red"; } } public class BlueColor : Color { public BlueColor() { col = "blue"; } } public abstract class Car { private Color color; public Color Color { get { return color; } set { color = value; } } public abstract void Show(); } public class BigCar : Car { public override void Show() { Console.WriteLine("big car " + Color.col); } } public class SmallCar : Car { public override void Show() { Console.WriteLine("small car " + Color.col); } } static void Main(string[] args) { Car car = new BigCar(); car.Color = new BlueColor(); car.Show(); car = new SmallCar(); car.Color = new RedColor(); car.Show(); } } }
标签:
原文地址:http://www.cnblogs.com/zkzk945/p/5114276.html