实验 21:观察者模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解观察者模式的动机,掌握该模式的结构;

2、能够利用观察者模式解决实际问题。

 

[实验任务一]:股票提醒

当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。

实验要求:

1. 提交源代码;

2. 提交类图;

//Observer.java

package shiyan21;

 

public interface Observer {

    public void buy();

    public void cry();

}

//Subject.java

package shiyan21;

 

import java.util.ArrayList;

 

public abstract class Subject {

    protected ArrayList<Observer> observers;

    public Subject(){

        observers=new ArrayList<>();

    }

    public void attach(Observer a){

        observers.add(a);

    }

    public void detach(Observer a){

        observers.remove(a);

    }

    public abstract void up();

    public abstract void down();

}

//Gufen.java

package shiyan21;

 

import java.util.ArrayList;

public class Gufen extends Subject{

    public void up(){

        System.out.println("****股份上涨5%****");

        for(Observer guan:observers){

            guan.buy();

            }

    }

    public void down(){

        System.out.println("****股份下跌5%****");

        for(Observer guan:observers){

            guan.cry();

            }

    }

}

//Gumin.java

package shiyan21;

 

public class Gumin implements Observer{

    private String name;

    public Gumin(String a){name=a;}

    public void buy(){

        System.out.println("股民"+name+"买了一些股票");

    }

    public void cry(){

        System.out.println("股民"+name+"哭了");

    }

}

//main.java

package shiyan21;

public class main {

    public static void main(String[] args) {

        Gufen f=new Gufen();

        Gumin g1=new Gumin("小张");

        Gumin g2=new Gumin("小王");

        f.attach(g1);

        f.attach(g2);

        f.up();

        f.down();

    }

}

posted @ 2023-12-09 20:42  会秃头的小白  阅读(6)  评论(0编辑  收藏  举报