Preface: [ Mode Overview ] ---------- by xingoo
Intention mode
Framework defines a class, when it has a different category, then the specific implementation.
For example, we designed a cross-system client software, Windows needs a show class, Linux needs a set, mac also need to set. In this way, they only need to extract a framework of co-operation programming class, the specific use to which the system then uses the corresponding class, a bit like the inside of C ++ templates.
Scenarios
1 part of a disposable implement the same class, leaving other portions to subclasses implement.
2 extracts a common portion of each subclass superclass becomes
Subclass 3 Extended control.
Mode structure
AbstractClass abstract class framework
abstract class AbstractClass{
public void action(){
step1();
step2();
newMethod();
}
abstract protected void step1();
abstract protected void step2();
abstract protected void newMethod();
}
Class specific subclass, extend
class Class1 extends AbstractClass{
protected void newMethod() {
System.out.println("class1 newMethod");
}
protected void step1() {
System.out.println("class1 step1");
}
protected void step2() {
System.out.println("class1 step2");
}
}
class Class2 extends AbstractClass{
protected void newMethod() {
System.out.println("class2 newMethod");
}
protected void step1() {
System.out.println("class2 step1");
}
protected void step2() {
System.out.println("class2 step2");
}
}
All codes
1 package com.xingoo.test.design.template;
2 abstract class AbstractClass{
3 public void action(){
4 step1();
5 step2();
6 newMethod();
7 }
8 abstract protected void step1();
9 abstract protected void step2();
10 abstract protected void newMethod();
11 }
12 class Class1 extends AbstractClass{
13 protected void newMethod() {
14 System.out.println("class1 newMethod");
15 }
16 protected void step1() {
17 System.out.println("class1 step1");
18 }
19 protected void step2() {
20 System.out.println("class1 step2");
21 }
22 }
23 class Class2 extends AbstractClass{
24 protected void newMethod() {
25 System.out.println("class2 newMethod");
26 }
27 protected void step1() {
28 System.out.println("class2 step1");
29 }
30 protected void step2() {
31 System.out.println("class2 step2");
32 }
33 }
34 public class Client {
35 private static AbstractClass class1 = new Class1();
36 private static AbstractClass class2 = new Class2();
37 public static void main(String[] args) {
38 class1.action();
39 class2.action();
40 }
41 }
operation result
class1 step1
class1 step2
class1 newMethod
class2 step1
class2 step2
class2 newMethod
Reproduced in: https: //my.oschina.net/u/204616/blog/544965