Decorate model believes that we are familiar with, is a "bangoffour" in one of the most commonly used mode, the realization is quite simple. If someone is unfamiliar, take a look at the decorate model of groovy exploration, which has an example to follow in this article.
This example is a classic example of coffee in a café, coffee with original coffee, and a variety of additions depending on the taste of the customer, such as ice, milk, sugar, and so on. Customers can choose not add, add the same or a variety, the various addition of coffee to buy the same price.
This example is the most classic example of the implementation of the decorate pattern. Here we want to use a custom range class to implement it.
We first define a base class to implement a custom range, all other types of coffee are its subclasses, so that all of our coffee types have the properties of the range class. Let's take a look at this base class:
package range;
class Base implements Comparable{
static protected types = ['Coffee','Ice','Milk','Sugar']
protected int index = 0
protected type
protected getIndex()
{
this.index = this.types.indexOf(type)
}
def next()
{
Factory.getObject(types[(index+1)%types.size()])
}
def previous()
{
Factory.getObject(types[index-1])
}
int compareTo(Object other)
{
index<=>other.index
}
}
In this base class, the variable "types" is all the type of coffee. Others, such as "Index" variables, "Next", "previous", and "CompareTo" methods, all have the same logic as those of the general custom range class.
The "type" variable and "GetIndex ()" are for the convenience of subclasses of the "base" class, that is, in subclasses of the "base" class, we do not use the following statement as a means of doing this:
this.index = this.types.indexOf(type)
Because the object of the subclass is not expected in the "Base" class, we use a factory method to enable the custom range class to obtain the traversed subclass object. As follows:
Factory.getObject(types[(index+1)%types.size()])
Or:
Factory.getObject(types[index-1])
Next, let's look at the factory class:
package range;
class Factory {
static def getObject(type)
{
Class clazz = Class.forName("range.${type}")
return clazz.newInstance()
}
}
It's also easy to get a coffee object by the type of coffee.
Next, it's our turn to go to the various coffee classes:
package range;
class Coffee extends Base{
def Coffee()
{
this.type = 'Coffee'
this.getIndex()
}
def description()
{
'Coffee'
}
def price()
{
10
}
}