Design Patterns usage in Java API: Strategy, Command, Adapter, Builder

Design Patterns Covered

This post is a continuation of my previous post about Design Patterns usage in Java API, where I covered: Template Method, Observer, Composite, Decorator.

In this post four design patterns are covered: Strategy, Command, Adapter, Builder.

 

Strategy

Description on wiki is here
In Java API Strategy is implemented in several places I would like to show you an example with Comparator and Collections.sort() method. For better understanding we would have to look at the Collections.sort(java.util.List, java.util.Comparator) method. As you can see this pattern gives us great flexibility i choosing the sorting algorithm. This is because sort method is taking a simple comparing interface as argument. Depending on a situation we can choose different algorithm to sort the same data.
Lets see a comparator implementation:

...
    public static Comparator<Location> cityLocationComparator = new Comparator<Location>() {
        @Override
        public int compare(Location lhs, Location rhs) {
            return lhs.getCity().compareTo(rhs.getCity());
        }
    };
...
    public static Comparator<Location> stateLocationComparator = new Comparator<Location>() {
        @Override
        public int compare(Location lhs, Location rhs) {
            return lhs.getState().compareTo(rhs.getState());
        }
    };
...

Comparator usage:

    public void setList(List<SBJobsite> list, boolean sortByCity) {
        if (sortByCity) {
            Collections.sort(list, cityLocationComparator);
        } else {
            Collections.sort(list, stateLocationComparator);
        }
        processList(list);
    }

 

Command

Description on wiki is here
This design pattern can be seen in all java.lang.Runnable related code. I have an example about using runnable with swing. In the code below Runnable object (command) is send to a method as argument and can be invoked at any time.

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                this.label.setText("Updated text");
            }
        };
        SwingUtilities.invokeLater(runnable);

 

Adapter

Description on wiki is here.
Adapter helps two incompatible interfaces to work together.
The example show translation of one interface (array) into another (list) using java.util.Arrays.asList(T… a) method.

        Integer[] spam = new Integer[] { 1, 2, 3 };
        List<Integer> integers = Arrays.asList(spam);

 

Builder

Description on wiki is here.
Builder is a Creational Pattern, and provides alternative for creating an object with constructor.
Example with StringBuilder shows that code look definitely better, then concatenated String would.

	public String getCreateMethod() {
		return new StringBuilder()
		.append("\t@Override\n")
		.append("\tpublic void onCreate(Bundle savedInstanceState) {\n")
		.append("\t\tsuper.onCreate(savedInstanceState);\n")
		.append(String.format("\t\tsetContentView(%s);\n", activityResource.getReference()))
		.append("\n")
		.append(getDeclaration())
		.append("\t}\n").toString();
	}

Applying Builder pattern in AlertDialog.Builder (android) makes the creation of AlertDialog look better, then it would look if we use constructor with corresponding number of parameters.

    private void showLocationNotEnabledDialog() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
        alertDialogBuilder.setTitle(R.string.location);
        alertDialogBuilder.setMessage(R.string.turn_on_network_location);
        alertDialogBuilder.setPositiveButton(R.string.location_access_settings, positiveButtonOnClickListener);
        alertDialogBuilder.setNegativeButton(R.string.cancel, negativeButtonOnClickListener);
        alertDialogBuilder.show();
    }

 

Reklamy

Skomentuj

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj / Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj / Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj / Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj / Zmień )

Connecting to %s