Often there are multiple subclasses in the program that have common methods that have similar calling procedures. At this time we can use template mode to solve these repetitive work, such as when we buy things are generally the choice of goods, payment, such as the steps, the difference is only the selection of the product variety is different, this time we can use template mode. So how does the template pattern need to be implemented, such as
The code is as follows:
public class Test
{
public static void Main (String args[])
{
Goods f=new fruit ();
F.run ();
Goods d=new drink ();
D.run ();
}
}
Class goods
{
void Run ()
{
Getgoods ();
Pay ();
}
void Getgoods ()
{
System.out.println ("get");
}
void Pay ()
{
SYSTEM.OUT.PRINTLN ("pay");
}
}
Class Fruit extends goods
{
void Getgoods ()
{
System.out.println ("fruit");
}
}
Class drink extends Goods
{
void Getgoods ()
{
System.out.println ("Drink");
}
}
Results
This allows us to avoid involving specific algorithms in subclasses, simply by extracting the duplicated content from the algorithm to the parent class, reducing the coupling.
At this point, we can also join a hook mechanism, can be corresponding to some of the unnecessary algorithms to control.
The code is as follows
public class Test
{
public static void Main (String args[])
{
Goods f=new fruit ();
F.run ();
Goods d=new drink ();
D.run ();
}
}
Class goods
{
void Run ()
{
if (Hasgetgoods ())
Getgoods ();
Pay ();
}
void Getgoods ()
{
System.out.println ("get");
}
Boolean hasgetgoods ()
{
return false;
}
void Pay ()
{
SYSTEM.OUT.PRINTLN ("pay");
}
}
Class Fruit extends goods
{
Boolean hasgetgoods ()
{
return true;
}
void Getgoods ()
{
System.out.println ("fruit");
}
}
Class drink extends Goods
{
Boolean hasgetgoods ()
{
return false;
}
void Getgoods ()
{
System.out.println ("Drink");
}
}
Results:
Contact me: [Email protected]
2016-8-3
21:25
Touch Plate mode and hooks