Template Method design pattern (C)

Template Method pattern is a very common pattern, but also we need to have a pair of sharp eyes, because the template method has many implementations, but they look the same design and are not necessarily talking about the book.

This pattern is common because of the creation framework, this model is simply fantastic. Controlled by a framework of how to do things, but (people who use this framework) framework specified in detail each step of the algorithm you.

Sort by template method

We often need an array to do something? correct! Sort.

Java array class designers to provide us with a convenient method used to sort of template. Let's see how this method runs:

There are two methods together to provide the sort of functionality, here are part of Java source code

public static void sort(Object[] a) {
    Object aux[] = (Object[])a.clone();
    mergeSort(aux, a, 0, a.length, 0);
}

private static void mergeSort(Object[] src, Object[] dest,int low,int high, int off) {
    // 这里省略其他实现
    int length = high - low;
    if (length < INSERTIONSORT_THRESHOLD) {
        for (int i=low; i<high; i++)
            for (int j=i; j>low &&
                     ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
                swap(dest, j, j-1);
        return;
    }
    // 这里省略其他实现
}

Sort duck

Join us there is a need to sort an array of ducks, how would you do? Sort template method has provided an array of algorithms, but you have to make the template method to know how to compare ducks. You have to do it is to implement a compareTo () method.

What happened was this: sort () method enables designers hope that for all of the array, so they turn out to be the sort of static methods, this way, any array can use this method. But it does not matter, it is to use and it is defined in the superclass is the same. Now, there is one detail to tell you: because sort is not really defined in the superclass, so sort method needs to know that you have achieved this compareTo method, otherwise it can not be sorted.

To achieve this, the designers use the Comparable interface. You must implement this interface, this method provides an interface declared, that is, compareTo ().

public class Duck implements Comparable<Duck> {
    String name;
    int weight;
  
    public Duck(String name, int weight) {
        this.name = name;
        this.weight = weight;
    }
 
    public String toString() {
        return name + " weighs " + weight;
    }
  
    public int compareTo(Duck object) {
 
        Duck otherDuck = object;
  
        if (this.weight < otherDuck.weight) {
            return -1;
        } else if (this.weight == otherDuck.weight) {
            return 0;
        } else { // this.weight > otherDuck.weight
            return 1;
        }
    }
}

Let's test this program

public class DuckSortTestDrive {

    public static void main(String[] args) {
        Duck[] ducks = { 
                        new Duck("Daffy", 8), 
                        new Duck("Dewey", 2),
                        new Duck("Howard", 7),
                        new Duck("Louie", 2),
                        new Duck("Donald", 10), 
                        new Duck("Huey", 2)
         };

        System.out.println("Before sorting:");
        display(ducks);

        Arrays.sort(ducks);
 
        System.out.println("\nAfter sorting:");
        display(ducks);
    }

    public static void display(Duck[] ducks) {
        for (Duck d : ducks) {
            System.out.println(d);
        }
    }
}

Observe the inner workings of the sort of duck

Let us work process tracking template methods sort Array class. We'll see how the template method is a control algorithm, and at some point in the algorithm how it requires us to provide a step ducks implemented

  1. First, we need an array of ducks
  2. Then sort the template method of the Array class, and pass an array of ducks
  3. Want to sort an array, you need to compare two items again and again, until the entire array are sorted
  4. If the order does not duck, to use specific methods swap swap both the Array
  5. Sort method will continue to compare and adjust the duck until the entire array order is correct

It is not very surprised, this is also a kind of template method to achieve it. Although the template method is not textbook, but its implementation is still in line with the spirit of the template method pattern . In the Java API, you can also see the other. Java.io such an InputStream class has a read () method is implemented by a subclass, and this method will be read (byte b [], int off, int len) method using a template.

There are templates and strategies models are packaged combination, a combination with an inheritance, you figured it out yet? If you're still too general, then, Xiao Bian you carefully open book "Head First Design Patterns" look at this chapter of it, then we'll discuss.

Design tool box

Time to summary

  • OO foundation

    Abstraction, encapsulation, inheritance, polymorphism

  • OO principles

    Change package

    Multi-purpose combination, less inheritance

    An interface for programming, not for the realization of programming

    Loosely coupled interaction between design objects and work

    Reliance abstract, do not rely on specific categories

    Class should be open for extension, closed for modification

    And talking to friends only

    Do not look for me, I will find you ( our latest principles remind you, by the super-class master of all, when they need to call naturally subclass, which like Hollywood )

    And talking to friends only

  • OO model

    "Strategy mode ',' observer mode ',' Decorator Pattern", "abstract factory pattern", "factory method pattern", "singleton", "command mode", "adapter mode", "look mode"

    " Template method pattern " in the definition of an algorithm of a method in skeleton, while deferring some steps to subclasses. Template methods such subclasses without changing the structure of the algorithm, some of the steps of the algorithm are redefined.

After completing the template method pattern, Xiao Bian know, the original in design mode frequently used in peacetime, he also occupies an important position, before learning, small series is completely unaware of it. This finally get into this mode, and the reserves of knowledge, but also slowly digested Oh.

Next time, we went into the World iterators and combination modes.

Love life, love of learning and perception, kicked love

Guess you like

Origin www.cnblogs.com/dimple91/p/10973134.html