Head First (three)--decorator mode

Source: Internet
Author: User
Tags class definition inheritance

This chapter can be referred to as "giving love a new vision of the people who inherit." This chapter will learn how to use object composition to decorate classes at run time. Once you are familiar with decorating techniques, you will be able to assign new responsibilities to your (or others ') objects without modifying any of the underlying code.

design principles : Classes should be open to extensions and closed to modifications.


Let's start by looking at what the object enhancement means:

Inheritance-enhanced objects are fixed, enhanced content is fixed decorator mode-enhanced objects can be toggled, enhanced content is fixed dynamic proxies-enhanced objects can be toggled, enhanced content can be toggled

Disadvantages of Inheritance:

1. Enhanced content is dead, can't move

2. The augmented object is also dead

Class Coffee {}

Class has sugar coffee extends coffee class {

}

Class plus milk coffee extends coffee class {

}

Class add salt coffee extends coffee class {

}

If you add sugar and milk,

Class add sugar and milk extends + milk {

}

The need for personalization, using inheritance, can lead to a burst of classes.

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

Decorator mode

1. Enhanced content is not modifiable

2. The enhanced object can be arbitrary

Class Coffee {}

Class has sugar coffee extends coffee class {

}

Class plus milk coffee extends coffee class {

}

Class add salt coffee extends coffee class {

} Coffee a = new plus sugar ();

Coffee B = new plus salt (a); To decorate a, is to add salt to a.

Coffee c = new plus salt (b);

Decorator mode is used much more in Java API IO streams.

IO Stream Classification:

1. Bytes: InputStream, OutputStream

2. Characters: Reader, Wirter

InputStream

FileInputStream: Node stream. is to bind to a resource. and the files on the disk are tied together.

Bufferedinputstream: It is a decorative stream. When creating me, be sure to give me a bottom-level object, I don't care what stream you give me, I'll add buffers to it.

New Bufferedinputstream (arbitrary InputStream)



ObjectInputStream is also a decorative flow.


Bytearrayinputstream is a node stream that binds to a byte array in memory.


Gzipinputstream is a decorative flow.

There are many decorative flows in Java io, and few node flows.

Decorator mode use: can be used to enhance a specific type of object that is not known to be enhanced.

Bufferedinputstream: You want to read a byte from Bufferedinputstream, Bufferedinputstream will go to disk to read the contents of a plastic bag first, then, give you a byte. You want to read the second byte, Bufferedinputstream will not have to go to disk to read, give you a second directly. This reduces the interaction with the disk. Because, the disk is very slow.

The bottom of the FileInputStream involves C code because it interacts with the local file system.

Bufferedinputstream bottom still need to use to FileInputStream, just, once take a plastic bag.

==================================

Decoration mode The decoration of the new house does not change the nature of the house, but it can make the building more beautiful, more warm and more practical. In software design, the functions of existing objects (new houses) are extended (renovated). The common function is encapsulated in the adorner, where it is used to make the call. Adornment mode is a technique used in place of inheritance, which uses an association relationship between objects to replace the inheritance relationship between classes. Introduce the decoration class, expand the new function. Roles, abstract artifacts, concrete components, abstract decorative classes, specific decorative classes.

==================================

Decorator mode can dynamically add some additional responsibilities to an object. For added functionality, the decorator mode is more flexible than generating subclasses.
the applicable environment for this mode is:
(1) adds responsibility to a single object in a dynamic, transparent manner without affecting other objects. The
(2) Handles those duties that can be undone.
(3) When the method of generating subclasses cannot be expanded. 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, resulting in an explosive increase in the number of subclasses. Another situation may be because the class definition is hidden, or the class definition cannot be used to generate subclasses.
Key steps to implement the pattern:
(1) Component (the object's base class): Defines the interface of an object that can dynamically add responsibilities to these objects;
(2) Concretecomponent (specifically decorated object): Define the specific object, Decorator can give it additional responsibilities;
(3) Decorator (Decorator abstract Class): maintains a reference to a component instance, Define an interface that is consistent with component (that is, to inherit or implement the base class of the object being adorned);
(4) Concretedecorator (concrete decorator): The specific decorative objects, to the internal holding of the specific decorative objects to add specific responsibilities;
In this way, we may have some bad understanding, then we still have the usual:
after winter, the weather is getting colder, after work, as a senior foodie, about two or three friends to a hot pot feast again cool. Speaking of hot pot, have to mention in Chengdu to eat the Big dragon Brigitte Hotpot, all kinds of pot, with all the dishes, but my favorite is the big dragon Brigitte Hotpot flavor pot, spicy beef, broadsword hair belly, day flavor sausage, Mound mound beef, spicy ribs, etc., think of all drooling ah. The
said that we combine the decorator's implementation steps, it should feel a little bit, the above mentioned the bottom of the pot , is actually the object of the decoration of the base class, ingredients is actually the decorator abstract class, Tai Lung Brigitte Hot pot flavor Pot These specific bottom of the pot is specifically decorated objects, spicy beef, broadsword hair belly, tian taste sausage, Mound mound beef, spicy ribs These decorative pot with a variety of various garnish that is the specific decorative objects. Say this, everyone should be enlightened, the following we begin the specific code implementation:

First step: Define the base class of the object being decorated (can be an abstract class or an interface)

Public interface Guodi {
	float cost ();//The bottom of the pot is of course a price.
	String name ();//Name must have a OH
}
Step two: Define the specific objects to be decorated (i.e., a variety of pots, defined here)
public class Yuanyang implements Guodi {
	@Override publicly
	float cost () {
		return 48.0f;
	}
	@Override public
	String name () {
		return "duck pot";
	}
}
public class Dalongyan implements Guodi {
	@Override publicly
	float cost () {
		return 59.0f;
	}
	@Override public
	String name () {
		return "big dragon Brigitte Hotpot pot";
	}
}
Step three: Define the adorner abstract class
Public abstract class Peicai implements Guodi {
	private guodi guodi;
	Public Peicai (Guodi guodi) {
		this.guodi = Guodi;
	}
	@Override public
	float cost () {
		return guodi.cost ();
	}
	@Override public
	String name () {
		return guodi.name ();
	}
}
Fourth step: Define the specific Adorner object
public class Malaniurou extends Peicai {public
	Malaniurou (Guodi guodi) {
		super (Guodi);
	}
	@Override public
	float cost () {
		return super.cost () + 46f;
	}
	@Override public
	String name () {
		return super.name () + "+ spicy beef";
	}
}
public class Maodu extends Peicai {public
	maodu (Guodi guodi) {
		super (Guodi);
	}
	@Override public
	float cost () {
		return super.cost () + 30f;
	}
	@Override public
	String name () {
		return super.name () + "+ broadsword belly";
	}
}
Test class:
public class Test {public
	static void Main (string[] args) {
		Guodi Guodi = new Dalongyan ();//Point A big dragon Brigitte Hotpot original
		pot Alaniurou y = new Malaniurou (guodi);//a spicy beef
		maodu x = new Maodu (y);//on the basis of spicy beef and then a machete Hairy belly
		System.out.println (" Altogether points: "+ x.name () +", total consumption: "+ x.cost ());}
}
Output Result:
A total of points: Big dragon Brigitte Hot pot Original pot + spicy beef + broadsword hair belly, consumption: 135.0
Transferred from: https://www.cnblogs.com/panhouye/p/6120232.html

Take a look at these two articles:

http://blog.csdn.net/luanlouis/article/details/19021803

http://blog.csdn.net/jason0539/article/details/22713711

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.