Shiv ENOW large front end
Company official website: CVTE(Guangzhou Shiyuan Stock)
Team: ENOW team of CVTE software Platform Center for Future Education
The author:
preface
There are often four stages in learning design patterns
- Did not learn before is also not understand, in a particular scenario can not think of a universal design way, design code is worse.
- After learning a few patterns, I am very happy to use the patterns I have learned, so I will misuse the patterns without realizing it.
- I have learned a lot of design patterns and feel that many of them are very similar. I cannot distinguish the differences between them, but I know that misuse is harmful, so I hesitate to apply them.
- Applying patterns flexibly, even without applying specific patterns, can design very good code to achieve the realm of swords without swords.
This series will explore the possibilities of TypeScript working with design patterns to design applications that are easy to maintain, expand, reuse, and be flexible.
What is object orientation
Object orientation is a style of programming in which code is written around objects rather than individual functions. There are many people and things in the world, and each of them can be regarded as an object, and each object has its own attributes and behaviors, and objects interact with each other through methods. Object oriented is a kind of “object” as the center of the programming idea, the problem to be solved into each object, the purpose of establishing the object is not to complete a step, but to describe a certain object in the whole step to solve the problem in the attribute and behavior.
TypeScript object-oriented fundamentals
We’ll use some small examples to help you learn some of the concepts of object-oriented programming.
The first step is to simply build an environment that allows us to debug our code better.
Let’s create a new folder and use it as a little repository for our practice
Global install TSC Run NPM install tsc-g in this directory
Generate a tsconfig.json file in this folder and run TSC –init
We will create two new folders, dist and SRC respectively, to store ts source files and compiled JS files
Modify the tsconfig.json file to add the following two configurations
RootDir refers to the path of ts files we write, and outDir refers to the path of output files we compile.
Create a new index.html file:
To make it easier to see the output and debugging of our code, we installed a vscode plug-in “live server” which can be used as a real-time server to view the development of the web page.
Once installed, you can right-click the index.html file and open it in your browser
Our environment is now complete.
Class and instance
Let’s look at class and instance definitions first
Class: An abstract collection of objects having the same properties and functionality.
Instance: An instance, also known as an object, is a self-contained entity identified by a set of recognizable characteristics and behaviors
Let’s say we have a circle now, and one of the methods is to draw a circle, and we do it in an object-oriented way and it’s going to look something like this
// Have a round class
class Circle {
draw() {
console.log('draw')}}// Instantiate the circle class
const circle = new Circle()
// Call the circle drawing method
circle.draw()
Copy the code
We can try to run the above code. We will create a new index.ts file under the SRC folder of the project we built earlier, and copy the above code into it.
And then we run it at the terminaltsc -watch
At this point, we can see that there is an extra index.js file in the dist folder, and we can add it to the index.html filescriptThe tag introduces the **”./dist/index.js”** file
Then we open it in the browser using the same method, and we can see the console output
The constructor
Constructors are class initializers that are automatically called every time a new class is created. In ES6 classes there is a special “contructor” method that represents the constructor
Assuming that our circle now needs to have a radius every time it initializes, we need to modify the above code a bit
class Circle {
// Declare a private variable of Circle radius stands for radius
private radius;
// Define the Circle constructor, passing in an argument of type number
constructor(radius: number) {
// Copy the passed parameters to the private radius variable
this.radius = radius
}
draw() {
console.log('the draw, the radius:.this.radius)
}
}
// When instantiating an object, you must pass in the parameters required by the constructor
const circle = new Circle(1)
circle.draw()
Copy the code
After the above modification, we need to pass in a radius value every time we create an instance of a circle, and the circle will automatically carry a radius attribute every time it is created. We save the code to run as follows:
Method overloading
Method overload definition: If two methods have the same method name but different parameters, then one method is an overload of the other.
But in our JS, there are two methods with the same name will be overwritten, so in our JS language method overloading actually does not need to repeatedly declare the function, just need to do different processing logic according to the function parameters can be realized.
Again, take our example above.
Now that we have to pass in a radius every time we create an instance of a circle, can we pass in the radius value and use the default value when we pass in the radius value?
class Circle {
private radius;
// Define the Circle constructor to make the RADIUS argument optional
constructor(radius? : number) {
if (radius) {
this.radius = radius
} else {
this.radius = 1}}draw() {
console.log('the draw, the radius:.this.radius)
}
}
// Instantiate circle1 without passing in an argument, using the default value
const circle1 = new Circle()
// instantiate circle2 and pass in argument 2
const circle2 = new Circle(2)
circle1.draw()
circle2.draw()
Copy the code
All we need to do is make radius parameters optional, and then do different things depending on the parameters passed in.
Run the above code effect:
Properties and modifiers
attribute
Suppose we now have a circle that also needs to have information about its position and can access that information by instance, what can we do
class Circle {
private radius;
// Declare a public property for the save location
public location: object;
constructor(radius? : number) {
if (radius) {
this.radius = radius
} else {
this.radius = 1
}
// Initialize the location information
this.location = {x: 1.y: 1}}draw() {
console.log('the draw, the radius:.this.radius)
}
}
const circle1 = new Circle()
circle1.draw()
// Access location information directly
console.log(circle1.location)
Copy the code
Run the code above:
The location information is the properties of the circle, and we can directly access the inner properties of the circle by instance.
But this way we can change the location property of the circle externally for example
class Circle {
private radius;
public location: object;
constructor(radius? : number) {
if (radius) {
this.radius = radius
} else {
this.radius = 1
}
this.location = {x: 1.y: 1}}draw() {
console.log('the draw, the radius:.this.radius)
}
}
const circle1 = new Circle()
circle1.draw()
// Modify the location attribute
circle1.location = 123
console.log(circle1.location)
Copy the code
Running the above code we will find that the value of our location has been changed and the data structure does not match the original
At this point we can use es6 getters and setter accessors to solve this problem.
class Circle {
private radius;
// Redeclare it private
private location: object;
constructor(radius? : number) {
if (radius) {
this.radius = radius
} else {
this.radius = 1
}
this.location = {x: 1.y: 1}}// Get accessors provide external access to internal attributes
get Location() {
return this.location
}
// Perform some validation on the assignment of the attribute, and throw an exception if it does not conform to the rule
set Location(obj: object) {
if(! obj.x || ! obj.y) {throw new Error('Invalid location')}this.location = obj
}
draw() {
console.log('the draw, the radius:.this.radius)
}
}
const circle1 = new Circle()
circle1.draw()
// Modify the location attribute
circle1.Location = 123
console.log(circle1.Location)
Copy the code
Run the above code
We see that the console throws an exception that we wrote, indicating that the assignment is not in compliance with the specification, so we have secured the value of the property.
The modifier
In each of the above examples, we see that the property declaration is preceded by a value private or public, which is essentially a modifier.
We can add modifiers before a method or property declaration. In TypeScript, property or method declarations without modifiers default to public
Modifiers generally fall into the following categories
public
Indicates that the class member it modifies can be accessed by any other class, public
private
Only members of the same class are allowed to access it. Other classes, including subclasses, are not allowed to access it. Private
protected
Indicates that the class member it modifies can be accessed in a derived class (subclass)
readonly
Keyword sets the property to read-only, which must be initialized at declaration time or in a constructor
The location property in the example above is an example. We made it public so that it could be called outside of the class, but then we didn’t want the property to be called directly outside of the class, so we made it private, Use getter setters to provide external reading and modification of the location property.
conclusion
Through this article today, we briefly introduced some basic concepts of object-oriented, and behind the most important three characteristics of object-oriented six principles and commonly used design patterns and other content will be slowly unveiled to you in the next article, please look forward to…
Refer to the article
- Big Talk Design Mode
- zhuanlan.zhihu.com/p/28427324