Android觀察者模式執行個體分析_Android

來源:互聯網
上載者:User

本文執行個體講述了Android觀察者模式。分享給大家供大家參考。具體分析如下:

一、環境:

主機:WIN8
開發環境:Eclipse

二、說明:

1.開啟sd卡中的xml檔案,如果不存在,這建立一個,並寫入預設配置
2.讀取xml檔案
3.Config_Info.java為配置資訊資料結構
4.IF_Config.java為配置類的存取介面,其他類可以通過此介面直接擷取配置資訊
5.IF_Subject_Config.java為觀察者模式目標類介面
6.IF_Observer_Config.java為觀察者模式觀察者類介面
7.Config.java為配置類,完成1,2兩部工作,同時是觀察者模式的目標類,一旦配置資訊由變化著通知觀察者類
8.TestClass.java為觀察者模式的觀察者
通過存取介面+觀察者模式可以實現松耦合的設計。

三、xml檔案格式:

<?xml version="1.0" encoding="UTF-8" standalone="true"?> -<config> <title>遠程視頻會見系統</title> <local_port>12600</local_port> <schedule_service_ip>10.58.1.59</schedule_service_ip><schedule_service_port>12601</schedule_service_port> </config>

四、原始碼:

Config_Info.java:

/**  * 配置資訊資料類型  * 建立時間:2014/12/8 by jdh  */ package com.example.helloanychat; public class Config_Info {  //標題  public String title;  //本機ip  public String local_ip;  //本機連接埠  public int local_port;  //調度伺服器ip  public String schedule_server_ip;  //調度伺服器連接埠  public int schedule_server_port; }

IF_Config.java:

/**  * 介面:配置類,讀寫  * 建立時間:2014/12/8 by jdh  */ package com.example.helloanychat; public interface IF_Config {  public Config_Info get_config_info(); }

IF_Subject_Config.java:

/**  * 介面:配置類,觀察者模式:目標  * 建立時間:2014/12/8 by jdh  */ package com.example.helloanychat; public interface IF_Subject_Config {  public void register_observer(IF_Observer_Config observer);  public void remove_observer(IF_Observer_Config observer);  public void notify_observer(); }

IF_Observer_Config.java:

/**  * 介面:配置類,觀察者模式:觀察者  * 建立時間:2014/12/8 by jdh  */ package com.example.helloanychat; public interface IF_Observer_Config {  public void update(Config_Info info); }

Config.java:

/**  * 配置資訊類  * 建立日期:2014/12/8 by jdh  * 修改日期:2014/12/9 by jdh  */ package com.example.helloanychat; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringWriter; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Timer; import java.util.TimerTask; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import android.os.Environment; import android.util.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; public class Config implements IF_Config,IF_Subject_Config {  //配置資訊  private Config_Info Info = new Config_Info();  //儲存觀察者的列表  private List<IF_Observer_Config> Observers = new ArrayList<IF_Observer_Config>();  //定時器  private Timer Timer_Work = new Timer();  //工作間隔,單位:ms  private final int INTERVAL_WORK = 5000;  /**  * 建構函式  */  public Config() {  //組建組態資訊  generate_config_info();  //建立定時線程  Timer_Work.schedule(new Task(),INTERVAL_WORK,INTERVAL_WORK); // 定時任務  }  //介面:讀寫  @Override  public Config_Info get_config_info() {  return Info;  }  //讀寫,觀察者模式:目標  @Override  public void register_observer(IF_Observer_Config observer) {  Observers.add(observer);  }  @Override  public void remove_observer(IF_Observer_Config observer) {  int index = Observers.indexOf(observer);  if (index >= 0) {   Observers.remove(observer);  }  }  @Override  public void notify_observer() {  for (int i = 0; i < Observers.size(); i++) {   IF_Observer_Config o = (IF_Observer_Config) Observers.get(i);   o.update(Info);  }  }  /**  * 得到本機ip地址  * @return 本機ip地址  */  private String getLocalIpAddress() {  try {   for (Enumeration<NetworkInterface> en = NetworkInterface    .getNetworkInterfaces(); en.hasMoreElements();) {   NetworkInterface intf = en.nextElement();   for (Enumeration<InetAddress> enumIpAddr = intf    .getInetAddresses(); enumIpAddr.hasMoreElements();) {    InetAddress inetAddress = enumIpAddr.nextElement();    //if (!inetAddress.isLoopbackAddress()) {    if (!inetAddress.isLoopbackAddress() && !(inetAddress instanceof Inet6Address)) {    return inetAddress.getHostAddress().toString();    }   }   }  } catch (SocketException ex) {   Log.e("WifiPreference IpAddress", ex.toString());  }  return null;  }  /**  * 產生xml設定檔的String資料流  * Config_Info的本機ip資訊不會儲存  * @param info:配置資訊  * @return xml的String資料流  */  private String produce_xml_string(Config_Info info) {  StringWriter stringWriter = new StringWriter();  try {   // 擷取XmlSerializer對象   XmlPullParserFactory factory = XmlPullParserFactory.newInstance();   XmlSerializer xmlSerializer = factory.newSerializer();   // 設定輸出資料流對象   xmlSerializer.setOutput(stringWriter);   //開始標籤   xmlSerializer.startDocument("utf-8", true);   xmlSerializer.startTag(null, "config");   //標題   xmlSerializer.startTag(null, "title");   xmlSerializer.text(info.title);   xmlSerializer.endTag(null, "title");   //本機連接埠   xmlSerializer.startTag(null, "local_port");   xmlSerializer.text(Integer.toString(info.local_port));   xmlSerializer.endTag(null, "local_port");   //調度伺服器ip   xmlSerializer.startTag(null, "schedule_service_ip");   xmlSerializer.text(info.schedule_server_ip);   xmlSerializer.endTag(null, "schedule_service_ip");   //調度伺服器連接埠   xmlSerializer.startTag(null, "schedule_service_port");   xmlSerializer.text(Integer.toString(info.schedule_server_port));   xmlSerializer.endTag(null, "schedule_service_port");   xmlSerializer.endTag(null, "config");   xmlSerializer.endDocument();  } catch (Exception e) {   e.printStackTrace();  }  return stringWriter.toString();  }  /**  * 工作任務:得到配置資訊  */  private void generate_config_info()  {  boolean ok;  File sd_path;  File file_cfg_dir;  File file_cfg;  FileOutputStream out;  String str;  FileInputStream in;  Config_Info info = new Config_Info();  //得到本機ip地址  info.local_ip = getLocalIpAddress();  //擷取SD卡目錄  sd_path = Environment.getExternalStorageDirectory();  //判斷檔案夾是否存在  file_cfg_dir = new File(sd_path.getPath() + "//Remote_Meeting");  if (!file_cfg_dir.exists() && !file_cfg_dir.isDirectory()) {   System.out.println("設定檔夾Remote_Meeting不存在!");   ok = file_cfg_dir.mkdirs();   if (ok) {   System.out.println("建立檔案夾成功!");  } else {   System.out.println("建立檔案夾失敗!");  }  }  //判斷設定檔是否存在  file_cfg = new File(file_cfg_dir.getPath(),"cfg.xml");  if (!file_cfg.exists())  {   System.out.println("設定檔cfg.xml不存在!");   try {   file_cfg.createNewFile();   System.out.println("建立檔案cfg.xml成功!");   //產生初始化的配置資料   try {    out = new FileOutputStream(file_cfg);    //儲存預設配置    Info.title = "遠程視頻會見系統";    Info.local_port = 12600;    Info.schedule_server_ip = "10.58.1.59";    Info.schedule_server_port = 12601;    str = produce_xml_string(Info);    out.write(str.getBytes());    out.close();    //儲存本機ip    Info.local_ip = info.local_ip;    //通知觀察者    notify_observer();   } catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }   } catch (IOException e) {   // TODO Auto-generated catch block   e.printStackTrace();   }  }  else  {   //解析xml檔案   try {   in = new FileInputStream(file_cfg);   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   DocumentBuilder builder = factory.newDocumentBuilder();   Document document = builder.parse(in);   // 擷取根節點   Element root = document.getDocumentElement();   NodeList node = root.getChildNodes();   //獲得第1子節點:標題   info.title = node.item(0).getFirstChild().getNodeValue();   //獲得第2子節點:本機連接埠   info.local_port = Integer.parseInt(node.item(1).getFirstChild().getNodeValue());   //獲得第3子節點:調度伺服器ip   info.schedule_server_ip = node.item(2).getFirstChild().getNodeValue();   //獲得第4子節點:調度伺服器連接埠   info.schedule_server_port = Integer.parseInt(node.item(3).getFirstChild().getNodeValue());   //判斷配置資訊是否變更   do   {    if (!info.title.equals(Info.title))    {    break;    }    if (!info.local_ip.equals(Info.local_ip))    {    break;    }    if (info.local_port != Info.local_port)    {    break;    }    if (!info.schedule_server_ip.equals(Info.schedule_server_ip))    {    break;    }    if (info.schedule_server_port != Info.schedule_server_port)    {    break;    }    //全部相同    return;   } while (false);   //賦值   Info.title = info.title;   Info.local_ip = info.local_ip;   Info.local_port = info.local_port;   Info.schedule_server_ip = info.schedule_server_ip;   Info.schedule_server_port = info.schedule_server_port;   //通知觀察者   notify_observer();   } catch (Exception e) {   e.printStackTrace();   }  }  }  /**  * 定時器線程定時工作  */  private class Task extends TimerTask {  @Override  public void run() {   generate_config_info();  }  } }

TestClass.java:

package com.example.helloanychat; public class TestClass implements IF_Observer_Config {  public TestClass () {  }  @Override  public void update(Config_Info info) {  System.out.printf("-------------更新資料:%s,%s,%d,%s,%d\n",  info.title,info.local_ip,info.local_port,info.schedule_server_ip,info.schedule_server_port);  } }

MainActivity:

TestClass testclass = new TestClass(); Config config = new Config(); mEditIP.setText(config.get_config_info().local_ip); config.register_observer(testclass); 

希望本文所述對大家的Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.