The introduction

The front-end has been unable to do object-oriented programming as well as strongly typed languages such as Java due to the language characteristics of JavaScript and some limitations, resulting in the arrival of ES6, class syntax sugar or TS object-oriented programming design is relatively weak. Next, record a small example to demonstrate class diagram design and code implementation

Example scenario

Usually take a taxi as an example:

1. There are express trains and special trains, which have license plates and names.

2, express train 2 yuan per kilometer, special train 4 yuan per kilometer;

3. Add a 5km trip;

Analysis of the

Each car has its license plate number and name. Cars can be divided into express and special cars. Cars can be abstracted into a parent class, and different cars inherit the parent class for instantiation. Each trip is done by car, so add a car and distance for each trip.

Draw a UML class diagram

The tool of choice is the popular online editing tool for ProcessOn, www.processon.com/

1. Draw the car’s parent class, which has two attributes: number and name. Add attributes and methods using +

2. Draw the trip class. We know that the trip depends on the car to complete, so the trip contains: Car and trip length attributes, and contains two behaviors: start the trip start() and end().

3. Draw the express subclass and the special subclass. Instances of cars have price attributes, and each car is different.

Express:

4, indicate inheritance and reference relationship, inheritance relationship using hollow arrow, instance pass using solid arrow

Code implementation and testing

Class Car {constructor() {constructor(); Name) {this.name = name this.number = number}} // Class Trip {constructor(car) length) { this.car = car this.length = length }start() {console.log(' Start of trip: name:${this.car.name}, license plate number:${this.car.number}`)}end() {console.log(' End of trip: price: ¥${this.car.price * this.length}Constructor (int) {constructor(int) {constructor(int) {constructor(int); Name) this. Price = 1}} class Zhuanche extends Car {constructor(number, name) {super(number, Name) this.price = 2}} // testlet car = new Kuaiche('Beijing A11010B'.'the BMW X5')
letTrip = new trip (car, 10) trip.start() // Trip: name: BMW X5, license plate: Beijing A11010B Trip.end (Copy the code

The purpose of this article is also to guide you to design and abstract some practical problems of a means of analysis and drawing, to better write excellent code.