Two main essentials of object-oriented

Source: Internet
Author: User

Original: http://cpper.info/2016/01/05/Two-Points-Of-Oriented-Object.html.

Overview

At the beginning of the work, we may often have this feeling, their code interface design confusion, code coupling is more serious, a class of code too much and so on, I look back at the time feel ashamed. Look at those well-known open source libraries, most of them have neat code, clear and simple interface, the responsibility of a single class, this time we will usually wringing and sigh: when the only way to write such code!

As novices, the reason we write something that is not prescriptive or unclear is the lack of some guiding principles. We wield the banner of object-oriented in our hands, and what is written is filled with the smell of process. Perhaps we do not know that there are these principles, perhaps we know but not very good use of the actual code, or we did not in the actual combat project to realize the advantages of these principles, so that we do not have enough attention to these principles.

Here, we will learn some of the key points, principles and patterns of object-oriented design.

Before that, it is important to know that familiarity with these principles will not allow you to write good code, but to pave the way for your good code, under the guidance of these principles, to avoid getting caught up in some common code mire, so that you can concentrate on writing good things.

This article will introduce you gradually:

    1. 2 main points of object-oriented
    2. 6 principles of Object-oriented
    3. 23 Design patterns of object-oriented

This section first introduces the 2 main points of object oriented.

The two main points of object-oriented programming for interfaces and not for implementation

Briefly

interface-oriented and implementation-oriented are based on the object-oriented pattern, that is, interface-oriented is not called a higher than object-oriented programming mode, but in the object-oriented large background of a more reasonable software design pattern, The interface here is not an implementation mechanism in a specific language (such as interface in Java), but rather a pattern at the software design level. Interface-oriented programming it enhances the low coupling between the class and the module, and makes the software system easier to maintain and extend.

To give a simple example, we often use the method of operating the database, defined in the JDK is the interface, by different database vendors, such as the MySQL driver, Oracle driver, is the implementation of the JDK defined interface standards. Database-driven design in JDK is interface-oriented, and different database vendors are implementation-oriented. The advantage of interface-oriented is that the definition of the interface standard, regardless of who just by the definition of the standard to achieve, can be seamless switch, so whether it is the use of MySQL or Oracle also, from the user level is the use of JDK API.

The main disadvantage of implementation-oriented programming is high coupling, which does not support expansion, while the main advantage of interface-oriented programming is low coupling and easy to expand.

Advantages

    • Clients do not know the exact type of object they are using
    • An object can be easily replaced by another object
    • Object does not require hard connection to an object of a special class, thus increasing flexibility
    • Loose coupling
    • Increased opportunity for reuse
    • Increases the chance of a combination because the contained object can be replaced by other objects that implement a particular interface

Disadvantages

    • Adds complexity to the design in some way

Example

Suppose we want to encapsulate an IO-multiplexed class, usually with a select, poll, Epoll model, and allow the user to choose a model by themselves, so it can be implemented through an inheritance system.

I/O multiplexing abstract interfaceClass poller{PublictypedefSTD::Vector<channel *> channellist;typedefSTD::Map<zl_socket, Channel *> channelmap;PublicExplicitPoller(EventLoop *loop);Virtual ~poller ();Create available backends based on various macro definitions and operating system differentiationStatic Poller *createpoller (EventLoop *loop);PublicAdd/Update the I/O events for sockets bound by channel, must be called in the main loopVirtualboolUpdatechannel(Channel *channel) =0;Delete the I/O events for the socket that the channel is bound to must be called in the main loopVirtualboolRemovechannel(Channel *channel) =0;All connections that respond to read and write events must be called in the main loopVirtual TimestampPoll_once(int Timeoutms, channellist &activechannels) =0;Get the description of the IO multiplexing backends currently in useVirtualConstchar* Iomultiplexername ()Const =0;Protected:channelmap CHANNELMAP_; EventLoop *loop_;};/*static*/poller* Poller::createpoller (EventLoop *loop) {#If defined (use_poller_epoll)ReturnNew Epollpoller (loop);#Elif defined (use_poller_select)ReturnNew Selectpoller (loop);#Elif defined (use_poller_poll)ReturnNew Pollpoller (loop);#Elsereturn NULL;#endifClass Selectpoller:Public poller{PublicExplicitSelectpoller(EventLoop *loop); ~selectpoller ();VirtualboolUpdatechannel(Channel *channel);VirtualboolRemovechannel(Channel *channel);Virtual TimestampPoll_once(int Timeoutms, channellist& activechannels);VirtualConstchar* Iomultiplexername ()const {Return"Select"; }Private:fd_set Readfds_;All readable events returned by select Fd_set Writefds_;All writable events returned by select Fd_set Exceptfds_;All error events returned by select Fd_set Select_readfds_;Add all the readable events of interest to the select Fd_set Select_writefds_;Add all writable events of interest to the select Fd_set Select_exceptfds_;All error events that are interested in adding to the SelectSTD::set<Intstd::greater<int> > Fdlist_;};Class Epollpoller:Public poller{PublicExplicitEpollpoller(EventLoop *loop,BOOL Enableet =FALSE); ~epollpoller ();VirtualboolUpdatechannel(Channel *channel);Virtualboolremovechannel (Channel *channel); virtual Timestamp poll_once (int Timeoutms, channellist& activechannels); virtual const char* ioMultiplexerName () const {return  "Linux_epoll";} private: typedef std::vector<struct epoll_event> EpollEventList; int epollfd_; bool enableet_; Epolleventlist Events_;};              

The above is a multi-state implementation of an IO multiplexing inheritance system. In the pure virtual base class (Poller), all interfaces to implement IO multiplexing are defined, while other subclasses (Selectpoller, Epollpoller) implement the respective functions for the interface. For the user, there is no need to consider the details of the content implementation, just according to the interface of the Poller class to use.

Prioritize use of combinations rather than inheritance (CARP)

Briefly

The two most common techniques for functional reuse in object-oriented systems are class inheritance and object composition (object composition).

Class inheritance allows you to define an implementation of a class based on the implementation of other classes. This multiplexing by generating subclasses is often referred to as white-box multiplexing (White-box reuse). The term "white box" is relative to the visibility: in the way of inheritance, the inner details of the parent class are visible to the child class, which can be said to be "broken encapsulation", any changes in the parent class implementation will inevitably lead to changes in the subclass, the degree of dependency between each other is high.

Object composition is a reusable selection other than class inheritance. New and more complex functions can be obtained by assembling or combining objects. Object combinations require that the objects being combined have well-defined interfaces. This reuse style is called black-box multiplexing (Black-box reuse) because the inner details of the object are not visible. Objects only appear in the form of "black boxes", with only a few concerns about the interfaces provided and a low dependency on each other.

Preference for combination rather than inheritance requires that we use composition rather than inheritance when reusing objects, because any change to the parent class can affect the behavior of the subclass when using inheritance, and when you use a combination, you get stronger functionality by getting a combination of other objects. and helps to maintain a single responsibility principle for each class.

Inheritance and composition each have advantages and disadvantages. Class inheritance is statically defined at compile time and can be used directly, because the programming language directly supports class inheritance. Class inheritance makes it easier to change the implementation that is reused. When a subclass is redefining some, but not all, operations, it can also affect the operations it inherits, as long as the redefined operation is invoked in those operations.

Prioritizing the use of object combinations helps you keep each class encapsulated and focused on a single task. Such class and class inheritance hierarchies remain small and are unlikely to grow into uncontrollable behemoths. On the other hand, design based on object composition will have more objects (and fewer classes), and the behavior of the system will depend on the relationship between objects rather than being defined in a class.

Example

Echo protocol refers to the server receives any data from the client and sends it back intact. If you want to implement a echoserver, according to the traditional practice, it is generally first to implement a TCPServer abstract class, set up a few virtual functions, such as connection arrival, data arrival, connection close and so on, this is the object-oriented polymorphism mechanism of the common implementation way. And here we demonstrate an implementation based on function callbacks.

Suppose we already have a EventLoop class that encapsulates IO multiplexing and a tcpserver class that can be used directly without any data processing. The TCPServer interface is as follows:

Class tcpserver:zl::noncopy{Public:tcpserver (EventLoop *loop,Const inetaddress& LISTENADDR);voidStart (); public:eventloop* getloop () const { return loop_;} void setconnectioncallback (const connectioncallback& cb) {connectioncallback_ = cb;} void setmessagecallback (const messagecallback& cb) {messagecallback_ = cb;} void setwritecompletecallback (const writecompletecallback& cb) {writecompletecallback_ = cb;}};   

Then a echoserver is easy to implement:

Classechoserver{Public:echoserver (EventLoop *loop,Const inetaddress& LISTENADDR);void start();  Private:/// callback void onConnection(const tcpconnectionptr& conn) When client connection is established or closed; ///The client has data sent over the callback void onMessage(const tcpconnectionptr& conn, Bytebuffer *buf,  const timestamp& time); Private:eventloop *loop_; TCPServer *server_;};               

The way to use it is simple:

loop;InetAddress listenAddr(port);EchoServer server(&loop, listenAddr);server.start();loop.loop();

This completes a echoserver.

Similarly, there is a simple daytime protocol, after the client connects to the server, the server returns a current time to the client. A daytimeserver can be implemented exactly as above.

This is also the object-oriented and object-based implementation of the differences, about the function callback as a substitute for the pure virtual function in the object-oriented way of the more introduction please refer to: Replace the virtual function with Boost::function and boost:bind.

Http://www.cnblogs.com/lizhenghn/p/5114674.html

Two main essentials of object-oriented (turn)

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.