Observer Pattern

Design_Patterns 02 Observer Pattern

Posted by Leonard Meng on October 20, 2021

Start from a Weather Observation Station

There is a weather observation station which takes the responsility of observe the weather condition. A TV station will get the data from weather station and show the weather condition to the public.

Design the system from object-oriented view

Obviously, there should be two classes: TV Station and Weather Observation Station. Therefore, Bob design the system like this:

TV Station

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class TVStation {
	
	private float mTemperature;
	private float mPressure;
	private float mHumidity;
	
	public void update(float mTemperature,float mPressure,float mHumidity)
	{
		this.mTemperature=mTemperature;
		this.mPressure=mPressure;
		this.mHumidity=mHumidity;
		display();
	}
	
	public void display()
	{
		System.out.println("***Today mTemperature: "+mTemperature+"***");
		System.out.println("***Today mPressure: "+mPressure+"***");
		System.out.println("***Today mHumidity: "+mHumidity+"***");
	}
}


Weather Observation Station

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class WeatherStation {
	
	private float mTemperatrue;
	private float mPressure;
	private float mHumidity;
	private TVStation tvStation;
	public WeatherStation(TVStation tvStation)
	{
	this. tvStation= tvStation;
	}
	
	public void dataChange()
	{
		tvStation.update(getTemperature(), getPressure(), getHumidity());
		}
	
	public void setData(float mTemperature,float mPressure,float mHumidity)
	{
		this.mTemperatrue=mTemperature;
		this.mPressure=mPressure;
		this.mHumidity=mHumidity;
		dataChange();
	}
	
}

The project is done. It looks well, isn’t it?

But let’s go further.

The problems of oo

There is a new requirement: another TV station wants to get the weather condition from Weather station. In order to finish the requirement, a new TV station object is must added to Weather Station Class. That’s the problem: For each additional observer, the weather station needs to add an object.

What caused the problem?

Directly passing in the instantiated object prevents the entire system from dynamically adding new objects.

Observer Pattern

Analyse the project

Before coding, we need to analyse the project: which parts always changing and which parts is stable?

  1. The display of a duck will not change.
  2. The behavior of a duck will change.

Flying behavior, quacking behavior and swimming behavior are various. In addition, they can be combined at will. Therefore, if one kind of behaviors is put into a cluster, the project will be easier.

What is Strategy Pattern?

Encapsulate the behavior interface respectively, implement the algorithm cluster, put the behavior interface object in the superclass, and set the behavior object in the subclass. The principle is: to separate the changing parts, encapsulate the interface, and program various functions based on the interface. This mode allows behavioural changes to the algorithm to be independent of the user of the algorithm.

Code the project from strategy pattern view

Fly behavior:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public interface Fly {
    void fly();
}
public class CanNotFly implements Fly{
    @Override
    public void fly() {
        System.out.println("I cannot fly~~~~~");
    }
}
public class CanFly implements Fly{
    @Override
    public void fly() {
        System.out.println("I can fly~~~~~");
    }
}

Quack behavior:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public interface Quack {
    void quack();
}
public class GegeQuack implements Quack{
    @Override
    public void quack() {
        System.out.println("Gege~~~~ Gege~~~~");
    }
}

public class GagaQuack implements Quack{
    @Override
    public void quack() {
        System.out.println("Gaga~~~~ Gaga~~~~");
    }
}

Duck:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public abstract class Duck {

    Fly fly;
    Quack quack;

    public Duck() {

    }

    public void Fly() {
        fly.fly();
    }

    public void Quack() {
        quack.quack();
    }

    public abstract void display();

    public void SetQuackBehavoir(Quack qb) {
        quack = qb;
    }

    public void SetFlyBehavoir(Fly fb) {
        fly = fb;
    }

    public void swim() {
        System.out.println("~~im swim~~");
    }
}

public class GreenDuck extends Duck{
    @Override
    public void display() {
        System.out.println("I am green duck");
    }

    public GreenDuck() {
        fly = new CanNotFly();
        quack = new GagaQuack();
    }
}
public class RedDuck extends Duck{
    @Override
    public void display() {
        System.out.println("I am red duck~~~~");
    }

    public RedDuck() {
        fly = new CanFly();
        quack = new GegeQuack();
    }
}

Object Oriented and Strategy Pattern

The problem of extends:

  1. The function in superclass will influence subclass.
  2. The fucntion in subclass is not reuseful.

The key points of Strategy:

  1. Analyze the changed and unchanged parts of the project.
  2. Use more combination and less inheritance; use behavior class combination instead of behavior inheritance. more flexible
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Welcome to reprint, and please indicate the source: Lingjun Meng's Blog Keep the content of the article complete and the above statement information!