Strategic model and observer model of design pattern in simple and simple way

Source: Internet
Author: User
Tags stub
Introduction to the first chapter

1. Here is a simple example of a duck example. Ducks will bark, they'll go, they'll swim (the same part). But some ducks can fly, some ducks look different and so on (become part), how to design it. By separating the invariant and variable parts, we draw our first design principle: Identify the changes that might be needed in the application, separate them, and not mix with the code that doesn't need to change.

2. How to design it. For the duck example above, we know that we want to enhance our code elasticity, that is, to make it easier to modify, to draw the second design principle: Programming for the interface, not for implementation . Specifically, for each variable behavior of our ducks, such as flight behavior, separate them out as an interface. The following figure


3. Next, you should integrate the Ducks behavior. In the previous process, we delegated the duck's variable Behavior (delegate) to Flaybehavior and Quackbehavior. The specific approach is to have the Ducks hold two instance variables of Flybehavior and Quackbehavior, and then write two methods, such as flight methods, as shown below

public void Performfly () {flybehavior.fly ();}

So Ducks have their own flying behavior, we only need to instantiate the duck, such as in the constructor to initialize the corresponding flight and name of the specific class can be.


4. Third design principle: multi-use combination, less inheritance.

The above tells a design patternstrategy mode, and is a multiple-policy model, there are flight strategies, there is a name of the strategy, different strategies under different implementations. Observer ModeThe Observer pattern applies to objects that are constantly changing and need to be monitored. The textbook example is a class webdata of the weather station, which can obtain the latest meteorological data and update it to three bulletin boards in a timely manner. The bulletin board cannot be just 3, and knowledge says there are now three, and there may be more billboards to show other data (scalability) later. How to do it. The basic process, we use a simple example to explain: if the observer is to subscribe to the newspaper people, referred to as dogs, ducks, cats and mice, they subscribe to a newspaper newspaper (if the Ducks have not subscribed). And the newspaper that is subscribed to, is the observer, call them the newspaper. The overall workflow is as follows: One day, the duck said to the newspaper, I would like to subscribe to a newspaper (ducks are quite observers), this process is called registration; newspaper Street subscription notification, add Ducks to your subscription list; Well, now ducks are also joining the viewer, and waiting for the newspaper to send the paper (send a notice); The newspaper printed out a new newspaper and told the watchers that the newspaper was ready;
The mouse did not want to be an observer and wanted to subscribe to another newspaper, so the mouse sent a request to the newspaper and the mouse left, removing an observer. The newspaper produced a new newspaper, but the mice had not been notified.
So we have a basic understanding of the workflow of the observer model, so the observer pattern should be specific how to achieve it. Let's look at the class diagram.
Be sure to pay attention to these methods, for the observed (subject, Subject), Registerobserver,removeobserver,notifyobserver, and for the Observer, only one update is required. This is a loosely coupled design, and the observer only needs to wait for the subject to be notified, while the subject only knows that the Observer has only one update method. The rest is easier. You can write a client class that is constantly registering an observer or removing an observer from the viewer by holding the two interfaces of the observer and the Observer. or the Notifyobservers () method is invoked by the client when the Observer needs to notify the observer.
Within Java, the Observer pattern is implemented, the Observervable abstract class is responsible for the observer, and the Observer interface is responsible for the observer, as shown in the following figure


Java's built-in observer pattern must go through two steps. That is, when the viewer updates the content, you must first Setchange () before calling Notifyobserver () to see the following code observer

Import java.util.Observable;
Import Java.util.Observer;

public class BlackBoard implements observer{

	@Override public
	void update (Observable o, Object Arg) {
		//TODO auto-generated method Stub
		if (O instanceof Teacher) {
			Teacher Teacher = (Teacher) o;
			System.out.println (Teacher.getcontent ());}}

The person being observed
Import java.util.Observable;

public class Teacher extends observable{
	private String content;
	Public Teacher () {
	
	} public
	
	void Measurementschanged () {
		setchanged ();
		Notifyobservers ();
	}

	public void SetContent (String content) {
		this.content=content;
		Measurementschanged ();
		
	}
	Public String getcontent () {
		//TODO auto-generated method stub return
		content;
	}

Client:
public class Client {public
	
	static void Main (string[] args) {
		Teacher t = new Teacher ();
		T.addobserver (New BlackBoard ());
		T.setcontent ("Course Content");		t.measurementschanged ();
		T.setcontent ("New Content");
	}


To sum up, the Observer pattern requires the following steps: 1. Create the Observer and the observed, where the observer needs to have an update () method, the observed person needs to have addobserver (), Removeobserver (), Notifyoverver () method. And even their own state. Setchange () indicates that the current data is not updated. 2. Registering an observer within the observer is irrelevant to the internal execution of the client or the observer, or even to the observer. 3, the observed updated content, set Setchange (), notify all Clients notifyobservers ().




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.