使设计模式的类图混合(Abstract Factory + Builder)代码

时间:2019-03-22 18:21:29

标签: c# design-patterns builder class-diagram abstract-factory

我从来都不是图用户,现在我必须为混合了两种不同设计模式(抽象工厂+生成器)的一段代码设计类图。

我尝试设计一个,但是我认为这是不正确的,有人可以帮我吗?

这是代码

namespace TestApp {
 class Program {
  static void Main(string[] args) {
   //Default car factory is used
   CarBuilder carBuilder = new CarBuilder();
   CarFactory carFactory = carBuilder.GetCarFactory();
   Console.WriteLine(carFactory.GetType());

   //Customer now wants to plugin his new class SportsCarFactory
   carBuilder.SetCarFactory(new SportsCarFactory());
   carFactory = carBuilder.GetCarFactory();
   Console.WriteLine(carFactory.GetType());
  }
 }

 ///
 /// This is a object builder class which returns abstract Carfactory
 ///
 public class CarBuilder {
  //This is a delegate function
  Func _factory;

  public CarBuilder() {
   //Lets set economical car factory as default car factory
   SetCarFactory(new EconomicalCarFactory());
  }

  //Get car factory returns the instance of car factory that is set
  public CarFactory GetCarFactory() {
   return _factory();
  }

  //This is the place where user can plugin his custom implemented
  //class that inherits CarFactory
  public void SetCarFactory(CarFactory carFactory) {
   _factory = () => carFactory;
  }
 }

 //We got abstraction for Car
 //Car can be sports car or economical car
 public abstract class Car {
  public abstract string CarType {
   get;
  }
 }

 //Economical car is more concrete, in the sense we have more details
 //which is, we know its an economical car
 public class EconomicalCar: Car {
  public override string CarType {
   get {
    return " Economical car";
   }
  }
 }

 //Sports car is more concrete, in the sense we have more details
 //which is, we know its a sports car
 public class SportsCar: Car {
  public override string CarType {
   get {
    return " Sports car";
   }
  }
 }

 //Car factory builds the car
 //It knows its building the car,
 //but doesnt know if the car is sports car or economical car
 public abstract class CarFactory {
  public abstract string FactoryType {
   get;
  }

  protected abstract Car BuildCar();

  //Both factories build cars
  public Car Build() {
   return this.BuildCar();
  }
 }

 //Economical car factory builds economical cars
 //More generalization of economical car factory is "car factory"
 public class EconomicalCarFactory: CarFactory {

  public override string FactoryType {
   get {
    return "Economical Car Factory";
   }
  }

  protected override Car BuildCar() {
   return new EconomicalCar();
  }
 }

 //Sports car factory builds sports cars
 //More generalization of sports car factory is "car factory"
 public class SportsCarFactory: CarFactory {

  public override string FactoryType {
   get {
    return "Sports Car Factory";
   }
  }

  protected override Car BuildCar() {
   return new SportsCar();
  }
 }
}

这是我到目前为止所做的

Here's what I've done so far

0 个答案:

没有答案