Design pattern-python java Decorator mode

Source: Internet
Author: User

decorator Pattern Definition     The responsibility is dynamically attached to the object. To extend functionality, decorators provide a more resilient alternative than inheritance

Implementing a class Diagram

    

features of decorator mode

A decorator and a decorated object have the same super-type . ( Note that this is the use of inheritance to achieve "type matching," rather than taking advantage of inheritance to get "behavior", behavior from decorators and base components, or a combination of relationships with other decorators )

B You can wrap an object with one or more adorners.

C because the decorator and the decorator have the same type, so any need for the original object of the occasion, can be replaced with decorative objects.

D decorators May, before and/or after the act entrusted to the decorator, add their own actions to achieve a specific purpose.

E objects can be decorated at any time, so you can decorate objects dynamically and without limits at runtime with your favorite decorators

decorator Pattern Implementation examples
Interface Widget {void Draw ();} 1. "Lowest common denominator" class TextField implements Widget {//3.   "Core" Class with "Isa" rel private int width, height;      Public TextField (int w, int h) {width = w;   Height = h;                                                } public void Draw () {System.out.println ("TextField:" + width + "," + height);}} 2.                           Second level base Classabstract class Decorator implements widgets {//with "Isa" relationship private Widget wid; 4.   "Hasa" Relationship public Decorator (Widget w) {wid = W;} public void Draw () {Wid.draw ();}//5. Delegation}class Borderdecorator extends Decorator {//6.   Optional Embellishment Public Borderdecorator (Widget W) {super (W);                                } public void Draw () {Super.draw (); 7.  Delegate to base class System.out.println ("Borderdecorator"); and add extRA stuff}}class Scrolldecorator extends Decorator {//6.   Optional Embellishment Public Scrolldecorator (Widget W) {super (W);                                } public void Draw () {Super.draw (); 7.  Delegate to base class System.out.println ("Scrolldecorator"); and add extra stuff}}//decorator can add his or her own behavior before or after the act of the delegate to achieve a specific purpose public class Decoratordemo {public static void Ma In (string[] args) {//8.                          Client have the responsibility to compose desired configurations Widget awidget = new Borderdecorator ( New Borderdecorator (New Scrolldecorator (New Textfie      LD (80, 24)));  Awidget.draw ();} }

The output is: textfield:80, 24
Scrolldecorator
Borderdecorator
Borderdecorator

A similar program that is implemented in contrast to the Python decoration pattern

def Bread (func):    def wrapper ():        print "</" "\>"        func ()        print "<\______/>"    Return Wrapperdef Ingredients (func):    def wrapper ():        print "#tomatoes #"        func ()        print "~salad~"    return wrapper@bread@ingredientsdef Sandwich (food= "--ham--"):    print foodif (__name__== "__main__"):    Sandwich ()

The JAVA I/O class uses the decorator pattern to implement many reading methods, and InputStream is the abstract component of the decorator. FilterInputStream is an abstract decorator, Linenumberinputstream is a concrete decorator, plus the ability to calculate the number of rows, Bufferinputstream is a plus buffered input function and ReadLine () The concrete decorator of the method

The following example is to write your own Java i./o adorner, converting all uppercase characters in the input stream into lowercase

Import Java.io.*;class Lowercaseinputstream extends Filterinputstream{public lowercaseinputstream (InputStream in) { Super (in);} Two read methods must be implemented one for byte array public int read () throws IOException {int c = super.read (); return (c = =-1? c:character.t Olowercase ((char) (c)));} public int read (byte[] b,int offset,int len) throws IOException {int result = Super.read (b, offset, len); for (int i =offset ; I < offset + result; i++) {B[i] = (byte) character.tolowercase ((char) b[i]);} return result;}} public class Inputtest {public static void main (string[] args) {int c;try{inputstream in = new Lowercaseinputstream (New Bu Fferedinputstream (New FileInputStream ("Test.txt")), while ((c = in.read ()) >= 0) {System.out.print ((char) c);} In.close ();} catch (IOException e) {e.printstacktrace ();}}




Design mode-python java Decorator mode

Related Article

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.