"JAVA design pattern" Decorator mode __java

Source: Internet
Author: User

Step one: Define a base class, where you need to decorate the method, the base class can be a class, can also be an interface

Public interface sourceable {public
   void method ();
}

Step two: Define a decorated class, inherit (implement) the base class

The public class Source implements sourceable{@Override the public
	void Method () {
		System.out.println ("This is Method one");
		
	}

}

Step three: Define an adorner, (directly or indirectly inheriting the base class) where the base class is implemented directly, or the direct subclass of the base class can be inherited.

To save an instance of a base class

public class decorator implements sourceable{

	private sourceable source;
	
	Public decorator (sourceable source) {
		super ();
		This.source=source;
	}
	
	@Override public
	Void Method () {
		System.out.println ("Decorate in front");
		Source.method ();
		System.out.println ("Decorate the Back");
	public void Method2 () {
		System.out.println ("Decorate in front");
		Source.method ();
		System.out.println ("Decorate the Back");
	}

Step Four: Test (note the way of the call, to the decorated person instance into the adorner)

public class Test {public
    static void Main (string[] args) {
		sourceable source=new source ();
		sourceable obj=new Decorator (source);
		Obj.method ();
	}


InputStream and OutputStream in IO use the decorator mode, where we use InputStream to simply record.



The decorated person is FilterInputStream


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

Decorated by Bufferedinputstream

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



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.