560 likes | 774 Views
Design Patterns in the Android Framework. Prof. Sheng-De Wang. What are Design Patterns?. In software engineering , a design pattern is a general reusable solution to a commonly occurring problem in software design. is not a finished design
E N D
Design Patterns in the Android Framework Prof. Sheng-De Wang
What are Design Patterns? • In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. • is not a finished design • is a description or template for how to solve a problem that can be used in many different situations. • Object-oriented design patterns typically show relationships and interactions between classes or objects. • Design patterns are widely used in the process of designing component-based systems
Definitions of Software Engineering • The application of engineering to software • Field of computer science dealing with software systems • large and complex • built by teams • exist in many versions • last many years • undergo changes • More definitions • Application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software (IEEE 1990) • Multi-person construction of multi-version software (Parnas 1978)
Object-Oriented Life Cycle • More time is spent in analysis and design, less time in implementation, testing and maintenance. • Life cycle phases intermix
Object-oriented (OO) design • The system is viewed as a collection of interacting objects. • The system state is decentralized and each object manages its own state. • Objects may be instances of an object class and communicate by exchanging messages.
OO Design Concepts • Design classes • Entity classes • Boundary classes • Controller classes • Inheritance—all responsibilities of a superclass is immediately inherited by all subclasses • Messages—stimulate some behavior to occur in the receiving object • Polymorphism—a characteristic that greatly reduces the effort required to extend the design
Android Framework • Android framework is based on object-oriented design • Part of Android Operating Systems What is a framework? Android Operating Systems
An important component • WebKit • An open source web page layout engine • Used in Apple’s Safari browser, Google’s Chrome Browser, … • Coded in C++ • Ported to Nokia Symbian OS, iPhone OS, Android OS, Palm’s WebOS, …
First android application example Inheritance enables software reuse.
An inheritance example package com.android.webviews; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.webkit.WebView; import android.webkit.WebViewClient; public class HelloWebView extends Activity { /** Called when the activity is first created. */ WebView webview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); webview = (WebView) findViewById(R.id.webview); webview.getSettings().setJavaScriptEnabled(true); webview.loadUrl("http://www.google.com"); }
webview.setWebViewClient(new HelloWebViewClient()); @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) { webview.goBack(); return true; } return super.onKeyDown(keyCode, event); } private class HelloWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } }
Software Frameworks • Components-Based Software Engineering means that we build software by "putting pieces together". • Frameworks provide the context in which the pieces can be used. • A framework may be seen as: • A reusable design of a system, • A skeleton of an application which can be customized by an application developer.
Component Frameworks • While frameworks in general describe a typical and reusable situation at a model level, a component frameworkdescribes a “circuit-board” with empty slots into which components can be inserted to create a working instance. Component Framework Coordination Services (transactions, persistence..)
Relationships Between Concepts Interface that satisfies contracts Component-type Specific interface Component implementation Independent deployment Component model Component Framework Coordination Services (transactions, persistence..)
The components-based software engineering aspects of the Android framework Key components (classes): Activity, Service, BroadcastReceiver, ContentProvider, Intent
Activity life cycle • Entire lifetime • Visible lifetime • Foreground lifetime • 3 nested loops • 7 hooks or callbacks
Frameworks and Patterns • It is important to realize that design patterns and frameworks are distinct concepts of different natures. • Frameworks are of a physical nature, and are executable software used in either the design or the run-time phase. • Design patterns are of a logical nature, representing knowledge of and experience gained with software.
Categories of Design Patterns • Creational Pattern: Deal with initializing and configuring of classes and objects. • Structural Patterns: Deal with decoupling interface and implementation of classes and objects • Composition of classes or objects • Behavioral patterns:Deal with dynamic interactions among societies of classes and objects • How they distribute responsibility
Defer object creation to another class Defer object creation to another object Describe ways to assemble objects Describe algorithms and flow control Design Pattern Space
Factory Method Pattern The Factory method lets a class defer instantiation to subclasses.
Android Example of Factory Method Pattern Activity View ... View= FactoryMethod() ... OnCreate() MyDraw GraphicView return new GraphicView OnCreate()
Android Example of Factory Method Pattern- code public class MyDraw extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new GraphicView(this)); } } public class GraphicView extends View{ private Paint paint= new Paint(); GraphicView(Context ctx) { super(ctx); } @Override protected void onDraw(Canvas canvas) { int line_x = 10; int line_y = 50; canvas.drawColor(Color.WHITE); paint.setColor(Color.GRAY); paint.setStrokeWidth(3); canvas.drawLine(line_x, line_y, line_x+120, line_y, paint); … } }
Composite Pattern Composite allows a group of objects to be treated in the same way as a single instance of an object.
Observer Pattern A subset of the asynchronous publish/subscribe pattern
Observer Pattern Example Observers Subject
Real time Market Data Feed Customer Customer Customer Customer Customer Example: Stock Quote Service Stock Quotes Observers
Model-View-Controller Pattern • Application of Observer Pattern • Benefits • Design reuse, Loose Coupling The solid line represents a direct association, the dashed an indirect association via an observer (for example).
MVC Pattern in Android • Cursor: model • ListView: view • Activity: control control SimpleCursorAdapter ListAdapter Cursor TextView ListView
More MVC example // Get a Spinner and bind it to an ArrayAdapter that // references a String array. Spinner s1 = (Spinner) findViewById(R.id.spinner1); ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.colors, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); s1.setAdapter(adapter); ArrayAdapter R Spinner XML
// Load a Spinner and bind it to a data query. private static String[] PROJECTION = new String[] { People._ID, People.NAME }; Spinner s2 = (Spinner) findViewById(R.id.spinner2); Cursor cur = managedQuery(People.CONTENT_URI, PROJECTION, null, null); SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, // Use a template // that displays a // text view cur, // Give the cursor to the list adatper new String[] {People.NAME}, // Map the NAME column in the // people database to... new int[] {android.R.id.text1}); // The "text1" view defined in // the XML template adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); s2.setAdapter(adapter2);
SimpeCursorAdapter cursor Spinner SQLite
Façade Pattern • A facade is an object that provides a simplified interface to a larger body of code, such as a class library.
Binder: IPC Mechanism of Android MediaPlayerBase: Interface of some concrete media player such as VorbisPlayer, PVPlayer
Playing a Video VideoView _player=(VideoView) findViewById(R.id.videoplay); Intent intent=this.getIntent(); _player.setVideoPath(intent.getDataString()); _player.start();
A video player with simple GUI import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.VideoView; public class VideoPlayer extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final VideoView w =(VideoView)findViewById(R.id.vdoplayer); Button cmdload = (Button)this.findViewById(R.id.cmd_load); cmdload.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { // TODO Auto-generated method stub w.setVideoPath("/sdcard/android/kongfu.mp4"); } }); Button cmdplay = (Button)this.findViewById(R.id.cmd_play); cmdplay.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { // TODO Auto-generated method stub w.start(); } }); Button cmdpause = (Button)this.findViewById(R.id.cmd_pause); cmdpause.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { // TODO Auto-generated method stub w.pause(); } }); } //end of onCreate() } //end of VideoPlayer
Some More Design Patterns • Proxy Pattern • Mediator Pattern • Bridge Pattern
Proxy Pattern • The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
Mediator Pattern • With the mediator pattern, communication between objects is encapsulated with a mediator object.
Bridge Pattern • “decouple an abstraction from its implementation so that the two can vary independently”