JAVA design Pattern (21)-Decorative (decorator) mode __java

Source: Internet
Author: User
Tags class definition

definition: dynamically adds some additional responsibilities to an object. Decorator mode is more flexible than generating subclasses in terms of adding functionality.

Type: Object-structured pattern

alias : Packing mode (wrapper)

class Diagram:



The decorator decoration pattern is a structured pattern that solves the problem of "excessive use of inheritance to extend the functionality of an object", which lacks flexibility because of the static nature introduced by the type, and as the number of subclasses increases (expanded functionality increases), The combination of the seed classes (the combination of extended features) can cause more subclasses to swell (multiple inheritance). Inheritance is the static trait introduced by a type meaning that the inheritance of a type to get functionality is at compile time. The so-called static, refers to at compile time, dynamic, refers to at runtime.


structure of decorative design patterns

Component: Defines an object interface that can dynamically add responsibilities to these objects. Concretecomponent: Defines an object that can dynamically add responsibilities to this object. Decorator: Maintains a pointer to a Component object, defines an interface that is consistent with the component interface, or implements the Component object directly.

Collaboration Relationship: Decorator sends requests from clients to the decorated concretecomponent to perform additional actions before and after sending the request.


Implementation Code

Implement the GSP and Bluetooth extensions for a phone with decorator mode

First, define the interface of a mobile phone or an abstract class, which is implemented using abstract classes, as follows:

Abstract interface--> Component abstract
class abstractcellphone{public
	abstract String callnumber ();
    Public abstract String SendMessage ();
}


Then, to implement the Android and iphone phone class, this class to inherit cellphone, that is, the Concretecomponent class in the diagram to inherit component, the implementation code is as follows:

Android phone-->concretecomponent
class Androidcellphone extends abstractcellphone{

	@Override
	Public String Callnumber () {return
		
		' Callnumber from Android terminal ';
	}

	@Override public
	String SendMessage () {return
		
		' SendMessage from Android terminal ';
	}
	
}
Class Iphonecellphone extends abstractcellphone{

	@Override public
	String Callnumber () {return
		
		" Callnumber from IPhone terminal ";
	}

	@Override public
	String SendMessage () {return
		
		' SendMessage from IPhone terminal ';
	}
}

Next you need to define an interface or abstract class decorator, implementing the following code:
Abstract interface--> Decorator
abstract class decorator extends abstractcellphone{
	protected Mcellphone;
	Public decorator (Abstractcellphone mcellphone) {
		this.mcellphone = Mcellphone;
	}
	@Override public
	String Callnumber () {return
		mcellphone.callnumber ();
	}
	@Override public
	String SendMessage () {return
		mcellphone.sendmessage ();
	}
}

Decorator inherits both Abstractcellphone and a private Abstractcellphone object. The meaning of this is that the Decorator class uses another component class. We can use one or more decorator objects to "decorate" a Component object, and the decorated object remains a Component object.

Then, to implement the GSP and Bluetooth extensions, they inherit from the decorator code as follows:

Specific decorative category GPS function extension  --> concretedecorator
class Decoratorgps extends decorator{public

	Decoratorgps ( Abstractcellphone mcellphone) {
		super (Mcellphone);
	}

	@Override public
	String Callnumber () {return
		super.callnumber () + GPS;
	}

	@Override public
	String SendMessage () {return
		super.sendmessage () + GPS;
	}
}
Class Decoratorbluetooth  extends decorator{public

	decoratorbluetooth (Abstractcellphone mcellphone) {
		super (Mcellphone);
	}

	@Override public
	String Callnumber () {return
		super.callnumber () + BlueTooth;
	}

	@Override public
	String SendMessage () {return
		super.sendmessage () + BlueTooth;
	}
}

Finally, the client invokes the code

//client client public class Decoratorclient {/** * @param args/public static void Main (string[)
		
		args) {Abstractcellphone mcellphone = new Androidcellphone ();
		
		System.out.println (Mcellphone.callnumber () + "\ n" +mcellphone.sendmessage ());
		
		System.out.println ("-------------------------------------------");
		
		Decorator GPS = new Decoratorgps (mcellphone);
		
		System.out.println (Gps.callnumber () + "\ n" +gps.sendmessage ());
		
		System.out.println ("-------------------------------------------");
		
		Decorator Bluetooth = new Decoratorbluetooth (mcellphone);
		
	System.out.println (Bluetooth.callnumber () + "\ n" +bluetooth.sendmessage ()); }
}


Advantages and disadvantages of decorator model
More flexible than static inheritance the decorator pattern provides a more flexible way to add responsibilities to objects, using add-and-detach methods, with decorations adding and removing responsibilities at run time. Adding responsibilities by using inheritance mechanisms requires creating a new subclass, if you need to add functionality to all of the original subclasses, each subclass needs to be rewritten to increase the complexity of the system, and it can provide multiple decorator for a particular component class, which is difficult to apply to inheritance. To avoid having too many features in a class at the top of a hierarchy, the decorator pattern provides a "pay-only" approach to adding responsibilities, and he does not attempt to support all the predictable features in a complex, customizable class, but instead can define a simple class, And with the decorator class to his gradual add function, can be composed from simple parts of complex functions. Decorator is not the same as its component decorator is a transparent packaging, if we from the point of view of object identification, a decorated component is different from this component, so the use of decoration should not since the object identity. Many small objects are produced, and the system design using the decorator pattern often produces many seemingly similar objects that differ only in the way they connect to each other.


Applicable Scenarios

Add responsibilities to a single object in a dynamic and transparent manner without affecting other objects to handle the duties that can be undone. When the method of generating subclasses cannot be extended, one scenario is that there may be a large number of independent extensions that will produce a large number of subclasses to support each combination, making the tree of the subclass explode, and possibly because the definition is hidden or the class definition cannot be used to generate subclasses.


Finally, I have a little puzzling, decorator can not inherit from the Component class to achieve the same function, but eventually inherited from Component, do not understand


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.