zoukankan      html  css  js  c++  java
  • java 观察者模式设计方法

     1 import java.util.Observable;
    2 import java.util.Observer;
    3 class House extends Observable {
    4 private float price;
    5 public House(float price){
    6 this.price=price;
    7 }
    8 public float getPrice(){
    9 return price;
    10 }
    11 public void setPrice(float price){
    12 super.setChanged();
    13 super.notifyObservers(price);
    14 this.price=price;
    15 }
    16 public String toString(){
    17 return "房子价格:"+this.price;
    18 }
    19 }
    20 class HousePriceObserver implements Observer{
    21 private String name;
    22 public HousePriceObserver(String name){
    23 this.name=name;
    24 }
    25 public void update(Observable obj,Object arg){
    26 if(arg instanceof Float){
    27 System.out.print(this.name+"观察者看到的价格:");
    28 System.out.println(((Float) arg).floatValue());
    29 }
    30 }
    31 }
    32 public class ObserDemo {
    33 public static void main(String[] args) {
    34 House h=new House(1000000);
    35 HousePriceObserver hp1=new HousePriceObserver("A");
    36 HousePriceObserver hp2=new HousePriceObserver("B");
    37 HousePriceObserver hp3=new HousePriceObserver("C");
    38 h.addObserver(hp1);
    39 h.addObserver(hp2);
    40 h.addObserver(hp3);
    41 System.out.println(h);
    42 h.setPrice(6666);
    43 System.out.println(h);
    44 }
    45 }
  • 相关阅读:
    Python集合(set)类型的操作
    3GPP接口定义及相关协议一览
    OSS基本概念介绍
    建造者模式(Builder Pattern)
    组合模式(Composite Pattern)
    观察者模式(Observe Pattern)
    ReentrantLock
    <logger>和<root>
    logback的configuration
    logback的加载过程
  • 原文地址:https://www.cnblogs.com/dennisac/p/2405151.html
Copyright © 2011-2022 走看看