Let you plug in wings (Decorator)

zhaozj2021-02-16  46

Extending your objects This is in a usual thing. The problem is, what should you do? Many options are not? For example, derived subclass

Yes. This is a good solution. But if it is in this case. We need to add a function during the run and have a client program.

To determine what functionally added. So can a simple extension subclass object do? So we must find a new way. Yes

You may have thought about the Decorator mode I have to say. It is to help you insert your wings when you want.

It is a very good way to combine it through an interface. Adapter mode is then done.

Public interface ing {public void install ();

So next. We want to insert a pair of real wings "Angel Wings" public class Angellwing: i {{public void install () {console.writeline ("Angel Wings");}}

Public Class Kingwing: i c {public void install () {console.writeLine ("Wings");}}

Public class decorator: iwing {private ion wing; // Wing interface docking preparation private string wingname; public decorator (ion w, string wn) {this.wing = W; this.wingname = wn;} public setwing (Iwing W, String Wn) {this.wing = W; this.wingname = Wn;}

Public void install () {decoratorwing (); wing.install ();} private void decoratorwing () {console.writeLine ("Insert ..." Wingname "...");}}

/ / Customer Call

Class client {public static int main (string [] args) {hing awing = new angellwing (); i d decoator = new decoator (awning, "天 之"); // Load the docking object decoator.install (); / / Actually put it into an angel wing

// If we change the reference to the wings, the actually loaded wings will also change awning = new kingwing (); decoator.install (); return;}}

Suppose if there are still a lot of wings to choose. Then it will be obvious on the role of decoator. Customer only needs to call one

Decoator's Install method is OK. And load the corresponding wing as a fitting. Like it is also used above

Gold wings. Ok. Decoator mode also introduced it.

转载请注明原文地址:https://www.9cbs.com/read-27426.html

New Post(0)