SlideShare uma empresa Scribd logo
1 de 25
Baixar para ler offline
Android Design
Pattern
Lucas Xu
1
In a nutshell
 MVC
 MVVM
 Observer
 Adapter
 Façade
 Bridge
 Factory
 Template
 Composition
 Decorator
2
MVC
 Model: data
 View: UI
 Controller: Logic
3
MVC - View
 res/layout/main.xml
http://developer.android.com/resources/tutorials/views/hello-gridview.html
<?xml version="1.0" encoding="utf-8"?>
<GridView
xmlns:android="http://schemas.android.com/apk/
res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
4
MVC - Controller
http://developer.android.com/resources/tutorials/views/hello-listview.html
 HelloGridView.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int
position, long id) {
Toast.makeText(HelloGridView.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
5
MVC - Model
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the
Adapter
public View getView(int position, View convertView,
ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled,
initialize some attributes
imageView = new ImageView(mContext);
6
MVC: all in one
 ListActiviy
Ref:
http://www.ideasandroid.com/archives/295
http://developer.android.com/reference/android/app/ListActivity.html
7
 Exercise
 Write your custom GridActivity
Variant – MVVM
Model View ViewModel
8
Ref:
http://en.wikipedia.org/wiki/Model_View_ViewModel
http://www.codeproject.com/KB/android/androidbinding.aspx
Android Binding
MVVM (cont’d)
 public static interfaceSimpleCursorAdapter
 bindView(View view, Context context, Cursor
cursor)
 ViewBinder
 setViewValue(View view, Object data, String
textRepresentation)
9
Ref:
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.ViewBinder.html
Observer
 BroadCastReciever
 Sensor Listener
 OnClickListener
 onClick
 OnCreateMenuListener
 onCreateContextMenu
 AsyncTask
 onProgressUpdate, onPostExecute
 Activity lifecycle callbacks (onStart, onResume, etc.) although with
only one dedicated subscriber.
 ?Many observerables support only one observer, how to extend?
 View.setOnClickListener(new OnClickListener())…
10
Observer (cont’d)
 Handler
 handleMessage()
 sendMessage()
 Single thread model v.s. Multiple thread
model
 Update UI in UI thread
 Looper, Handler , MessageQueue
 Kill Thread
11
Observer (cont’d)
 UI Sync:
 ES 文件浏览器
 ListView, GridView, etc,
 Delete, add, rename file .
 App alliance
 App downloading
 Downloading cancelled/ failed
 App installed
12
Adapter
 View
 AdapterView
 ExpandableListView
 Gallery
 GridView
 ListView
 Spinner
13
Data
Adapter
View
ListView
GridView
CustomView
Data Source
Content Provider
SharedPreference
Resources
SQLite
File System
public interfaceAdapter
abstract int getCount()
abstract Object getItem(int position)
abstract long getItemId(int position)
abstract int getItemViewType(int position)
abstract View getView(int
position, View convertView, ViewGroup parent)
abstract int getViewTypeCount()
abstract boolean hasStableIds()
abstract boolean isEmpty()
abstract void registerDataSetObserver(DataSetObserver observer)
abstract void unregisterDataSetObserver(DataSetObserver observer)
14
Adapter (cont’)
 ArrayAdapter<T>
 BaseAdapter
 CursorAdapter
 HeaderViewListAdapter
 ListAdapter
 ResourceCursorAdapter
 SimpleAdapter
 SimpleCursorAdapter
 SpinnerAdapter
 WrapperListAdapter
Façade
 A facade is an object that provides a
simplified interface to a larger body of
code, such as a class library.
 wrap a poorly-designed collection of APIs
with a single well-designed API (as per task
needs).
 Hide Complexity
 App network
 ExchangeViewManager
15
Façade (cont’d)
Android Media Framework
16
Bridge
 "decouple an abstraction from
its implementation so that the two can
vary independently“
17
Adapter
CursorAdapter
SimpleCursorAdapter
ArrayAdapter
AdapterView
AdapterViewFlipper
ExpandableListView
Gallery
Factory Method
 Defer instantiation to subclasses
18
View
Activity
ListView
OnCreate()
ListActivity
OnCreate()
...
View= FactoryMethod()
...
return new ListView
Factory Method (cont’d)
 View.
 protected Dialog onCreateDialog(int id)
Builder
 AlertDialog.Builder builder = new
AlertDialog.Builder(this);
19
Template
 Activity
 onCreate()
 AsyncTask
 doInBackground()
20
Composition
 Group sub objects, treated as a single
instance
 View, View Group, etc.
21
Composition (cont’d)
 View
 ViewGroup
 ? Why does ViewGroup subclass View,
what pattern is used?
 ?交换的小把手有很多样式,用哪种设计模式?
22
public abstract class ViewGroup extends View implements ViewParent{
private View[] mChildren;
…
}
Reference:
GOF: Design Pattern, chap 2
23
http://www.adakoda.com/adakoda/2010/01/20/ASPH_AW_REV1.pdf
Decorator
 java.io.BufferedInputStream(InputStream)
 java.io.DataInputStream(InputStream)
 java.io.BufferedOutputStream(OutputStre
am)
 java.util.zip.ZipOutputStream(OutputStrea
m)
24
25

Mais conteúdo relacionado

Mais procurados

JavaScript Patterns and Principles
JavaScript Patterns and PrinciplesJavaScript Patterns and Principles
JavaScript Patterns and Principles
Aaronius
 
Zend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View EnhancementsZend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View Enhancements
Ralph Schindler
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2
Alessandro Molina
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in android
Jay Kumarr
 

Mais procurados (20)

JavaScript Patterns and Principles
JavaScript Patterns and PrinciplesJavaScript Patterns and Principles
JavaScript Patterns and Principles
 
Android Effective UI: Tips, Tricks and Patterns
Android Effective UI: Tips, Tricks and PatternsAndroid Effective UI: Tips, Tricks and Patterns
Android Effective UI: Tips, Tricks and Patterns
 
Meetup angular http client
Meetup angular http clientMeetup angular http client
Meetup angular http client
 
Beyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and moreBeyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and more
 
Zend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View EnhancementsZend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View Enhancements
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2
 
Type of angular 2
Type of angular 2Type of angular 2
Type of angular 2
 
Android the Agile way
Android the Agile wayAndroid the Agile way
Android the Agile way
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for Beginners
 
MVVM In Use
MVVM In UseMVVM In Use
MVVM In Use
 
Soft serve prism
Soft serve prismSoft serve prism
Soft serve prism
 
AngularJS
AngularJSAngularJS
AngularJS
 
Angular Js
Angular JsAngular Js
Angular Js
 
Angular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanAngular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir Kaufman
 
Introduction To Model View Presenter
Introduction To Model View PresenterIntroduction To Model View Presenter
Introduction To Model View Presenter
 
Angular.js interview questions
Angular.js interview questionsAngular.js interview questions
Angular.js interview questions
 
Introduction to AngularJS Framework
Introduction to AngularJS FrameworkIntroduction to AngularJS Framework
Introduction to AngularJS Framework
 
Kalp Corporate Angular Js Tutorials
Kalp Corporate Angular Js TutorialsKalp Corporate Angular Js Tutorials
Kalp Corporate Angular Js Tutorials
 
Feature driven development
Feature driven developmentFeature driven development
Feature driven development
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in android
 

Destaque

Design Patterns
Design PatternsDesign Patterns
Design Patterns
soms_1
 

Destaque (14)

Implementing the Adapter Design Pattern
Implementing the Adapter Design PatternImplementing the Adapter Design Pattern
Implementing the Adapter Design Pattern
 
Android (software) Design Pattern
Android (software) Design PatternAndroid (software) Design Pattern
Android (software) Design Pattern
 
MVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,MobileMVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,Mobile
 
Acrhitecture deisign pattern_MVC_MVP_MVVM
Acrhitecture deisign pattern_MVC_MVP_MVVMAcrhitecture deisign pattern_MVC_MVP_MVVM
Acrhitecture deisign pattern_MVC_MVP_MVVM
 
Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)
 
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland KuhnReactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
 
Advance Android Layout Walkthrough
Advance Android Layout WalkthroughAdvance Android Layout Walkthrough
Advance Android Layout Walkthrough
 
Why MVC?
Why MVC?Why MVC?
Why MVC?
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Architectural Design Pattern: Android
Architectural Design Pattern: AndroidArchitectural Design Pattern: Android
Architectural Design Pattern: Android
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Tugas3 rekayasa web
Tugas3 rekayasa web Tugas3 rekayasa web
Tugas3 rekayasa web
 
From Maps to Apps the Future of Drone Technology
From Maps to Apps the Future of Drone TechnologyFrom Maps to Apps the Future of Drone Technology
From Maps to Apps the Future of Drone Technology
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 

Semelhante a android design pattern

Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
Guy Nir
 

Semelhante a android design pattern (20)

Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
Beginning Native Android Apps
Beginning Native Android AppsBeginning Native Android Apps
Beginning Native Android Apps
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics
 
Android development
Android developmentAndroid development
Android development
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?
 
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
 
Material Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROID
Material Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROIDMaterial Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROID
Material Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROID
 
Android Materials Design
Android Materials Design Android Materials Design
Android Materials Design
 
Compose In Practice
Compose In PracticeCompose In Practice
Compose In Practice
 
07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdf
 
06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and Container
 
Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018
 
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJSMeteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in android
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
 
2007 Zend Con Mvc Edited Irmantas
2007 Zend Con Mvc Edited Irmantas2007 Zend Con Mvc Edited Irmantas
2007 Zend Con Mvc Edited Irmantas
 
Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

android design pattern

  • 2. In a nutshell  MVC  MVVM  Observer  Adapter  Façade  Bridge  Factory  Template  Composition  Decorator 2
  • 3. MVC  Model: data  View: UI  Controller: Logic 3
  • 4. MVC - View  res/layout/main.xml http://developer.android.com/resources/tutorials/views/hello-gridview.html <?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/ res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" /> 4
  • 5. MVC - Controller http://developer.android.com/resources/tutorials/views/hello-listview.html  HelloGridView.java public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this)); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show(); } }); } 5
  • 6. MVC - Model public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); 6
  • 7. MVC: all in one  ListActiviy Ref: http://www.ideasandroid.com/archives/295 http://developer.android.com/reference/android/app/ListActivity.html 7  Exercise  Write your custom GridActivity
  • 8. Variant – MVVM Model View ViewModel 8 Ref: http://en.wikipedia.org/wiki/Model_View_ViewModel http://www.codeproject.com/KB/android/androidbinding.aspx Android Binding
  • 9. MVVM (cont’d)  public static interfaceSimpleCursorAdapter  bindView(View view, Context context, Cursor cursor)  ViewBinder  setViewValue(View view, Object data, String textRepresentation) 9 Ref: http://developer.android.com/reference/android/widget/SimpleCursorAdapter.ViewBinder.html
  • 10. Observer  BroadCastReciever  Sensor Listener  OnClickListener  onClick  OnCreateMenuListener  onCreateContextMenu  AsyncTask  onProgressUpdate, onPostExecute  Activity lifecycle callbacks (onStart, onResume, etc.) although with only one dedicated subscriber.  ?Many observerables support only one observer, how to extend?  View.setOnClickListener(new OnClickListener())… 10
  • 11. Observer (cont’d)  Handler  handleMessage()  sendMessage()  Single thread model v.s. Multiple thread model  Update UI in UI thread  Looper, Handler , MessageQueue  Kill Thread 11
  • 12. Observer (cont’d)  UI Sync:  ES 文件浏览器  ListView, GridView, etc,  Delete, add, rename file .  App alliance  App downloading  Downloading cancelled/ failed  App installed 12
  • 13. Adapter  View  AdapterView  ExpandableListView  Gallery  GridView  ListView  Spinner 13 Data Adapter View ListView GridView CustomView Data Source Content Provider SharedPreference Resources SQLite File System
  • 14. public interfaceAdapter abstract int getCount() abstract Object getItem(int position) abstract long getItemId(int position) abstract int getItemViewType(int position) abstract View getView(int position, View convertView, ViewGroup parent) abstract int getViewTypeCount() abstract boolean hasStableIds() abstract boolean isEmpty() abstract void registerDataSetObserver(DataSetObserver observer) abstract void unregisterDataSetObserver(DataSetObserver observer) 14 Adapter (cont’)  ArrayAdapter<T>  BaseAdapter  CursorAdapter  HeaderViewListAdapter  ListAdapter  ResourceCursorAdapter  SimpleAdapter  SimpleCursorAdapter  SpinnerAdapter  WrapperListAdapter
  • 15. Façade  A facade is an object that provides a simplified interface to a larger body of code, such as a class library.  wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).  Hide Complexity  App network  ExchangeViewManager 15
  • 17. Bridge  "decouple an abstraction from its implementation so that the two can vary independently“ 17 Adapter CursorAdapter SimpleCursorAdapter ArrayAdapter AdapterView AdapterViewFlipper ExpandableListView Gallery
  • 18. Factory Method  Defer instantiation to subclasses 18 View Activity ListView OnCreate() ListActivity OnCreate() ... View= FactoryMethod() ... return new ListView
  • 19. Factory Method (cont’d)  View.  protected Dialog onCreateDialog(int id) Builder  AlertDialog.Builder builder = new AlertDialog.Builder(this); 19
  • 20. Template  Activity  onCreate()  AsyncTask  doInBackground() 20
  • 21. Composition  Group sub objects, treated as a single instance  View, View Group, etc. 21
  • 22. Composition (cont’d)  View  ViewGroup  ? Why does ViewGroup subclass View, what pattern is used?  ?交换的小把手有很多样式,用哪种设计模式? 22 public abstract class ViewGroup extends View implements ViewParent{ private View[] mChildren; … } Reference: GOF: Design Pattern, chap 2
  • 24. Decorator  java.io.BufferedInputStream(InputStream)  java.io.DataInputStream(InputStream)  java.io.BufferedOutputStream(OutputStre am)  java.util.zip.ZipOutputStream(OutputStrea m) 24
  • 25. 25