Android programming: Observer Pattern Design, android observer

Source: Internet
Author: User

Android programming: Observer Pattern Design, android observer

Android programming: Observer Pattern Design


For more information, see http://blog.csdn.net/jdh99, :jdh.


Environment:

HOST: WIN8

Development Environment: Eclipse


Note:

1. Open the xml file in the SD card. If it does not exist, create a new one and write the default configuration.

2. Read xml files

3. Config_Info.java is the configuration information Data Structure

4. IF_Config.java is the access interface of the configuration class. Other classes can directly obtain the configuration information through this interface.

5. IF_Subject_Config.java is the object class interface of the observer mode.

6. IF_Observer_Config.java is the observer class interface in observer mode.

7. Config. java is the configuration class, which completes two jobs: 1 and 2. It is also the target class of the observer mode. Once the configuration information changes, it notifies the observer class.

8. TestClass. java is the observer of the Observer mode.


The loose coupling design can be achieved through the access interface + observer mode.


Xml file format:

<? Xml version = "1.0" encoding = "UTF-8" standalone = "true"?> -<Config> <title> Remote Video Conferencing System </title> <local_port> 12600 </local_port> <strong> 10.58.1.59 </schedule_service_ip> <schedule_service_port> 12601 </schedule_service_port> </config>

Source code:

Config_Info.java:

/* ** Configuration information data type * Creation Time: 2014/12/8 by jdh */package com. example. helloanychat; public class Config_Info {// title public String title; // local ippublic String local_ip; // Local Port public int local_port; // scheduling server ippublic String schedule_server_ip; // scheduling Server Port public int schedule_server_port ;}

IF_Config.java:

/*** Interface: configuration class, read/write * Creation Time: 2014/12/8 by jdh */package com. example. helloanychat; public interface IF_Config {public Config_Info get_config_info ();}

IF_Subject_Config.java:

/*** Interface: configuration class, observer mode: Target * Creation Time: 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 policy_observer ();}

IF_Observer_Config.java:

/*** Interface: configuration class, observer mode: Observer * Creation Time: 2014/12/8 by jdh */package com. example. helloanychat; public interface IF_Observer_Config {public void update (Config_Info info );}

Config. java:

/*** Configuration information class * creation date: by jdh * modification date: 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 c Lass Config implements IF_Config, IF_Subject_Config {// configuration information private Config_Info Info = new Config_Info (); // store the observer List private List <IF_Observer_Config> Observers = new ArrayList <IF_Observer_Config> (); // Timer private Timer Timer_Work = new Timer (); // work interval, unit: msprivate final int INTERVAL_WORK = 5000;/*** constructor */public Config () {// generate configuration information generate_config_info (); // create a scheduled thread, Timer_Work.schedule (new Task (), INTERVAL _ WORK, INTERVAL_WORK); // scheduled task} // interface: read/write @ Overridepublic Config_Info get_config_info () {return Info;} // read/write, observer mode: target @ Overridepublic void register_observer (IF_Observer_Config observer) {Observers. add (observer) ;}@ Overridepublic void remove_observer (IF_Observer_Config observer) {int index = Observers. indexOf (observer); if (index> = 0) {Observers. remove (observer) ;}@overridepublic void yy_observer () {For (int I = 0; I <Observers. size (); I ++) {IF_Observer_Config o = (IF_Observer_Config) Observers. get (I); o. update (Info) ;}}/*** get local IP Address * @ return local IP Address */private String getLocalIpAddress () {try {for (Enumeration <NetworkInterface> en = NetworkInterface. getNetworkInterfaces (); en. hasMoreElements ();) {NetworkInterface intf = en. nextElement (); for (Enumeration <InetAddress> enumIpAddr = intf. get InetAddresses (); 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;}/*** generate the String data stream of the xml configuration file * The local ip address of Config_Info is not saved * @ param info: configuration information * @ return xml String data stream */private String produce_xml_string (Config_Info info) {StringWriter stringWriter = new StringWriter (); try {// get XmlSeria Lizer object XmlPullParserFactory factory = XmlPullParserFactory. newInstance (); XmlSerializer xmlSerializer = factory. newSerializer (); // sets the output stream object xmlSerializer. setOutput (stringWriter); // start the xmlSerializer tag. startDocument ("UTF-8", true); xmlSerializer. startTag (null, "config"); // The title xmlSerializer. startTag (null, "title"); xmlSerializer. text (info. title); xmlSerializer. endTag (null, "title"); // The local port xmlSerializer. startTag (Null, "local_port"); xmlSerializer. text (Integer. toString (info. local_port); xmlSerializer. endTag (null, "local_port"); // scheduling server ipxmlSerializer. startTag (null, "schedule_service_ip"); xmlSerializer. text (info. schedule_server_ip); xmlSerializer. endTag (null, "schedule_service_ip"); // The scheduling server port xmlSerializer. startTag (null, "schedule_service_port"); xmlSerializer. text (Integer. toString (info. schedule_server_port); xm LSerializer. endTag (null, "schedule_service_port"); xmlSerializer. endTag (null, "config"); xmlSerializer. endDocument ();} catch (Exception e) {e. printStackTrace ();} return stringWriter. toString ();}/*** job: Get configuration information */private void generate_config_info () {boolean OK; File sd_path; File file_1__dir; File file_cfg; FileOutputStream out; string str; FileInputStream in; Config_Info info = new Config_Info (); // get Local IP address info. local_ip = getLocalIpAddress (); // obtain the SD card directory sd_path = Environment. getExternalStorageDirectory (); // determine whether the folder contains file_pai_dir = new File (sd_path.getPath () + "// Remote_Meeting"); if (! File_pai_dir.exists ()&&! File_cmd_dir.isdirectory () {System. out. println ("the configuration folder Remote_Meeting does not exist! "); OK = file_pai_dir.mkdirs (); if (OK) {System. out. println (" folder created successfully! ");} Else {System. out. println (" An error occurred while creating the folder! ") ;}}// Determine whether the configuration File exists file_cfg = new File (file_pai_dir.getpath ()," cfg. xml "); if (! File_cfg.exists () {System. out. println ("the configuration file cfg. xml does not exist! "); Try {file_cfg.createNewFile (); System. out. println (" the file cfg. xml is created successfully! "); // Generate the Initialization Configuration data try {out = new FileOutputStream (file_cfg); // Save the default configuration Info. title = "Remote Video Conferencing System"; 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 (); // Save the local ip Info. local_ip = info. local_ip; // notify the observer notify_observer ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackT Race () ;}} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} else {// Parse xml file try {in = new FileInputStream (file_cfg); DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); DocumentBuilder builder = factory. newDocumentBuilder (); Document document = builder. parse (in); // obtain the root node Element root = document. getDocumentElement (); NodeList node = root. getChildNodes ();// Get 1st subnodes: title info. title = node. item (0 ). getFirstChild (). getNodeValue (); // obtain the 2nd subnode: The local port info. local_port = Integer. parseInt (node. item (1 ). getFirstChild (). getNodeValue (); // get 3rd subnodes: Scheduling server ipinfo. schedule_server_ip = node. item (2 ). getFirstChild (). getNodeValue (); // obtain the 4th subnode: Scheduling server port info. schedule_server_port = Integer. parseInt (node. item (3 ). getFirstChild (). getNodeValue (); // determines whether the configuration information has changed 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); // value 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 the observer notify_observer ();} catch (Exception e) {e. printStackTrace () ;}}/ *** timer thread timed work */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 () {}@ Overridepublic void update (Config_Info info) {System. out. printf ("------------- update data: % 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);


Reference link:

1. http://blog.csdn.net/crave_shy/article/details/21235855

Related Article

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.