Select a travel mode based on the actual situation.
When you go out on Sunday, you can walk, ride, or take a bus.
Each person chooses a different method based on factors such as person or environment.
A simple factory is compatible with this type. You only need to know which method to use when running.
Create an abstract class Base:
Public abstract class Base {public abstract string Mode ();}Source Code
The following three categories are created: Bus, ycling, and Walk. They must overwrite the abstract method of the abstract class.
Public class Bus: Base {public override string Mode () {return this. GetType (). Name ;}}Source Code
Public class ycling: Base {public override string Mode () {return this. GetType (). Name ;}}Source Code
Public class Walk: Base {public override string Mode () {return this. GetType (). Name ;}}Source Code
Since it is a simple factory, in this factory class, it determines which method to run according to the condition. This method generally uses static to implement static.
Public class Factory {public static Base Trip (int speed) {if (speed <= 7) return new Walk (); if (speed> 7 & speed <= 20) return new ycling (); if (speed> 20) return new Bus (); return null ;}}Source Code
Now, we can run the factory method written above on the console: