C # Basics (2)

Source: Internet
Author: User

Abstract: Object-oriented programming is an important idea in many programming languages. All things are objects. There are many different kinds of personal understanding, in fact, with more, can also be able to understand and understand this thought.  Personal understanding: A class or interface, is the object, object-oriented is the operation of the class or interface, for example, to use a non-static class, you need to first a new object of this class, the inheritance interface needs to implement the method in the interface. This blog mainly involves some code notes and summaries of the previous learning object-oriented.

content: 1, Richter replacement principle 2, polymorphic virtual Method 3, Polymorphic abstract class 4, plant design mode 5, interface

--------------------------------------------------------------------------------------------------------------- -------------

Facing objects (three major characteristics, five Principles):

three major features: encapsulation, inheritance, polymorphism

Five main principles:

Single principle: An object should contain only a single responsibility, and the responsibility is fully encapsulated in a class. If too many responsibilities are encapsulated in a class, these responsibilities will interfere with each other while executing concurrently

Open closure principle: Open for extension, closed for modified code (mainly consider security)

Dependency reversal principle: high-level (Heigh leve1) modules should not be directly dependent on low-leve1 modules. Two of them should rely on abstraction

Richter substitution principle: Subclasses can replace their parent class

Interface Isolation principle: The client should not rely on interfaces that it does not need

--------------------------------------------------------------------------------------------------------------- ----------------

Encapsulation: Encapsulation class, encapsulation Method--solving code redundancy

Inheritance: Subclass Inherits Parent class

1, the Richter replacement principle

A, subclasses can be assigned to the parent class

If there is a method that requires a parent class as a parameter, we can pass the first subclass object, for example: You need an type of object as a parameter, you can pass any type of argument (any subclass inherits object)


B, if the parent class is loaded with a subclass object, you can strongly convert the parent class to a child class object

2. The virtual method of polymorphism

Object-oriented polymorphism benefits: ① solves code redundancy ▲②: Masks the differences between subclasses, writes out common code, applies to each subclass of the call

Use of virtual methods:

//Parent Class Public classPerson 
{Public string Name {get; set;} PublicPerson (stringname) { This. Name =name;
} Public Virtual voidSayHello () {Console.WriteLine ("I am a human being"); }//sub-class ① Public classchinese:person{ PublicChinese (stringName):Base(name) {} Public Override voidSayHello () {Console.WriteLine ("I am Chinese, my name is {0}", This. Name); }
}//sub-class ② Public classAmerica:person { PublicAmerica (stringName):Base(name) {} Public Override voidSayHello () {Console.WriteLine ("I'm an American, my name is {0}", This. Name); } }//Invoke instance:Chinese ch =NewChinese ("Zhang San"); America A1=NewAmerica ("Steve Jobs"); Person[] per={CH,A1}; for(inti =0; I < per. Length; i++) {Per[i]. SayHello ();
} //results: The SayHello method for two sub-classes

 Above example: The method of the parent class is marked as a virtual method, using the keyword virtual, this method can be re-written by the subclass .

Add a virtual to the method of the parent class, precede the method of the subclass with an override, and if the subclass's method is not preceded by an override, the compiler will not error, but in this case, the subclass's method cannot be called by the parent class . Because this method is a unique method of a subclass, the name is the same as the parent class, regardless of the parent class. A method of calling subclasses from a parent class that masks differences between subclasses

3, Polymorphic abstract class: (Commonly used: Factory design mode)

Problem: Using polymorphism to think about the area of a circle and a rectangle: the area of a circle is different from that of a rectangular area, how do you mask the differences between subclasses by writing a parent class and then calling the parent class? Parent class cannot construct method body at all

//Parent class:   Public Abstract classGraph { Public Abstract DoubleGetarea ();//abstract class has no method entity  }//sub-class ①: Round  Public classCircle:graph { Public DoubleRGet;Set; }  PublicCircle (Doubler) { This. R =R; }     Public Override DoubleGetarea () {returnMath.PI * R *R; }  }//Subclass ②: Rectangle Public classrectangle:graph{ Public DoubleHight {Get;Set; }  Public DoubleWidth {Get;Set; }  PublicRectangle (DoubleWidthDoublehight) {    This. Width =width;  This. Hight =hight; }   Public Override DoubleGetarea () {returnWidth *Hight; }}//Invoke instance:Graph GH =NewCircle (3)DoubleCirclearea= GH. Getarea ();//to find the area of a circleGraph GH2 =NewRectangle (2,4.2);DoubleRearea = Gh2. Getarea ();//Find Rectangular Area

Features of abstract classes:

 Abstract members in an abstract class must be marked abstract and cannot have any implementations.  A method cannot have any implementation that means that the method has no curly braces and no method body. Only curly braces, methods without method body are called NULL implementations.

B, abstract members must be marked in an abstract class

C, Abstract classes are constructors, but abstract classes cannot be instantiated

When a subclass inherits an abstract class, it must override all the abstract members in the parent class . (You can not rewrite the subclass unless it is also an abstract class)

E, you can include instance members in an abstract class, and they can be implemented without subclasses

The above example shows: Do not know how to write the parent class method, through the new subclass to implement abstract methods, shielding the differences between subclasses. The above simply uses abstract classes, often used in: factory design Patterns

4, Factory design mode:

Participant: Product: Abstract products class that abstracts and extracts the public code of a specific product class into an abstract product class (abstract method of abstract class)

Concerteproduct: Specific product classes that encapsulate the relevant code for the various product objects that need to be created into a specific product class (inheriting the respective methods of subclasses of the abstract class)

Factory: Factory class, provides a factory class to create a variety of products, in the factory class to provide a way to create a product, the method can be different from the parameters of the input to create different product objects

Client: Only the factory method of the factory class is called, and the corresponding method is passed to obtain the Product object (Implementation).

5. Interface:

Features: A, interface is a specification as long as a class inherits an interface, this class must implement all the members of the interface

B, interfaces cannot be instantiated, which means that objects cannot be created

C, interface and interface can inherit and can inherit more, the interface cannot inherit a class

D, the member in the interface cannot be added to the adornment defaults think public

The interface is very large: the first implementation of multi-inheritance, but also commonly used: different layers through the call interface to improve security (example: The business logic layer calls the interface of the data session layer).

Implementing the Publish subscription pattern (Observer mode): We as subscribers do not have to check this public number every time there are no new articles published, the public number as a publisher will be at the appropriate time to notify us (inherit the interface)

We are no longer strongly coupled with the public number. The public number doesn't care who subscribed to it, whether you're a man or a girl or a pet dog, it just needs to be posted to all subscribers on a regular basis (traversing subscribers)

Summary: When to use virtual methods to achieve polymorphism? When do you use abstract classes to achieve polymorphism? When do I use interfaces to achieve polymorphism?

Among the classes I have given you, if you can abstract a parent class, and the parent must write the methods common to these subclasses, and then you do not know how to write this method, use abstract classes to write the polymorphic .
Conversely, the abstract parent class, the method can write, and I also want to create the object of the parent class, using virtual methods .
In these categories there is no parent class, but they all have a common act and common ability. This is the time to use the interface to implement polymorphic

Object-oriented polymorphism is really a very abstract thing, the specific use can be based on the requirements, according to business logic to choose.

C # Basics (2)

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.