Select a travel mode based on the actual situation.

Source: Internet
Author: User

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:


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.