Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Chapter 4.

Design Pattern

2020-2021
COMP3330 Interactive Mobile Application Design and Programming
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
Console Programming vs.
Mobile App Programming
 Console programming:
 write the code
 compile it
 run and debug it

 Mobile app programming:


 design the interface (i.e.,
screen layout of the
application) (by code or with
the help of interface builder)
 work on code and interface
alternately (similar to
building web pages), define
their interaction

2
What is Design Pattern?
A well-established way to group application functions into
objects
Variations of it have been around at least since the early days of
Smalltalk, one of the very first object-oriented languages.
A high-level pattern:
It addresses the architecture of an application and classifies
objects according to the general roles they play in an
application, rather than drilling down into specifics.
Creates a miniature universe for the application, populated with
distinct kinds of objects
Specifies roles and responsibilities for each type of objects and
specifies the way they’re supposed to interact with each other.
3
An Analogy (MVC Design Pattern)
Consider a big flat-screen television…
Model:
A particular television program (can in fact be
played on different TV set)
View:
Television screen (can in fact show different
television programs)
Controller:
The circuitry and signal that pull the show off the
cable and then sends it to the screen

4
Common Design Patterns
Model View Controller (MVC)
Model View Presenter (MVP)
Model View ViewModel (MVVM)

5
Model View Controller (MVC)
Model:
Represents the data models
Manages the data states
Has business logics
View:
The way we represent our data
e.g. views / layouts in Android
Renders the UI
Controller:
Handles user interactions with our application
The communication channel between the model and the view
e.g. the fragments / activities in Android.
6
Model View Controller (MVC)

The user interacts with the UI, and the controller gets notified via the view.
Based on the User interaction the controller modifies certain Models.
Models perform some business logic and return the updated model data
state to the controller.
The controller can then update the UI according to the new data state as
received from Model.
7
Model View Controller (MVC)

8
Model View Presenter (MVP)
Model:
Same as in MVC pattern
View:
The way we represent our data
e.g. Views / layouts as well as activities / fragments in Android.
Will implement an interface for the Presenter’s Actions
Presenter:
Has no relation to the views (unlike MVC)
Operations are invoked by our views
Views are updated via View’s Interface.

9
Model View Presenter (MVP)

In MVP, the View and Presenter interact via an interface (unlike MVC).
Presenter performs some actions on the Interface, which is
implemented in Views and hence the view gets updated.

10
Model View Presenter (MVP)

Presenter interacts with


ViewActions interface but not
the view directly.
(Don’t need to worry about
Android APIs.)
11
Model View ViewModel (MVVM)
Model:
Same as in MVC/MVP pattern
View:
Binds to observable variables and actions exposed by the
ViewModel.
ViewModel:
Responsible for wrapping the model and preparing observable
data needed by the view. It also provides hooks for the view to
pass events to the model.

12
Model View ViewModel (MVVM)

So the View receives the User interactions and will notify the View
Model
Now the View Model will update the model as well as the Observable
(which will invoke the value change). Next, the View will update the UI
based on the Observable values.

13
Model View ViewModel (MVVM)

14
MVC vs. MVP vs. MVVM

You may refer to the following site for more details:


https://academy.realm.io/posts/eric-maxwell-mvc-mvp-and-mvvm-on-android/

15
Simple HCF Calculator Example in
Android Studio with MVC Design Pattern

Given 2 input numbers,


the HCF of the 2 numbers
will be calculated.

Note: MVC is the default design


pattern in Android Studio.

16
Simple HCF Calculator Example in Android
Studio with MVC Design Pattern (View)

XML for the above UI


<LinearLayout <EditText
xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/txtbox2"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="300px"
android:orientation="vertical" android:layout_height="200px"
android:layout_width="match_parent" android:text=""
android:layout_height="match_parent" android:textSize="18sp">
tools:context="hkucs.calculator2.MainActivity"> </EditText>

<EditText
android:id="@+id/txtbox1"
android:layout_width="300px"
android:layout_height="200px"
android:text=""
android:textSize="18sp">
</EditText>

17
Simple HCF Calculator Example in Android
Studio with MVC Design Pattern (View)

XML for the above UI


<TextView
android:id="@+id/lbl1"
android:layout_width="300px"
<Button
android:layout_height="wrap_content"
android:id="@+id/button1"
android:text=""
android:layout_width="300px"
</TextView>
android:layout_height="200px"
</LinearLayout>
android:text=“FIND HCF"
</Button>

18
Simple HCF Calculator Example in Android
Studio with MVC Design Pattern (Controller)

Java source code


– All Android classes are
import android.support.v7.app.AppCompatActivity; inherited from Activity
import android.os.Bundle; (old) or
AppCompatActivity
import android.view.View; (new) superclass.
import android.widget.Button; – You must override the
import android.widget.EditText; onCreate() methods in
import android.widget.TextView; Activity /
AppCompatActivity
superclass.
public class MainActivity extends AppCompatActivity {
Button button1;
EditText txtbox1,txtbox2;
TextView tv;

19
Simple HCF Calculator Example in Android
Studio with MVC Design Pattern (Controller)

Java source code

/** Called when the activity is first created. */


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Interconnection
txtbox1= (EditText) findViewById(R.id.txtbox1); between view
button1 = (Button) findViewById(R.id.button1); and model
tv = (TextView) findViewById(R.id.lbl1); (components in
txtbox2= (EditText) findViewById(R.id.txtbox2); UI  variables in
program)
button1.setOnClickListener(new clicker());
}

20
Simple HCF Calculator Example in Android Studio
with MVC Design Pattern (Model – Data State)
class clicker implements Button.OnClickListener
{ Inner class
public void onClick(View v)
{ Integer.parseInt() → cast a text
into an integer.
String a,b;
int x, y, hcf = 0;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
x = Integer.parseInt(a);
y = Integer.parseInt(b);
for(int i = 1; i <= x || i <= y; i++) {
if( x % i == 0 && y % i == 0 )
hcf = i;
}
tv.setText("HCF = " + String.valueOf(hcf));
}
String.valueOf() → convert an
}
integer into a string
} 21
Simple HCF Calculator Example in
Android Studio with MVC Design Pattern

Link up values on
UI and variables in
program

Accept input X & Y Compute


Display HCF(X, Y) HCF(X, Y)

22
More about Event Handling

Three concepts:
Event Listener − An interface (a role) in the View class
that contains a single callback method (handler). This
method will be called by the Android framework when
the View to which the listener has been registered is
triggered by user interaction.
Event Listener Registration − This is the process by
which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event
Listener fires the event.
Event Handler − When an event happens, the Event
Listener calls the Event Handler, which is the method
that actually handles the event.
23
Approach 1
Create an anonymous implementation of OnClickListener

private OnClickListener myInterestingListener = new OnClickListener() { // Event Listener


public void onClick(View v) { // Event Handler
// Do something interesting when the button is clicked
}
};

protected void onCreate(Bundle savedValues) {


...
// Capture our button from layout
Button button = (Button)findViewById(R.id.interesting);
// Register the onClick listener with the implementation above
button.setOnClickListener(myInterestingListener); // Event Listener Registration
...
}

24
Approach 2
If you want to avoid creating a class with just one method…

public class ExampleActivity extends AppCompatActivity


implements OnClickListener { // Event Listener

protected void onCreate(Bundle savedValues) {


...
Button button = (Button)findViewById(R.id.interesting);
button.setOnClickListener(this); // Event Listener Registration
}
// Implement the OnClickListener callback
public void onClick(View v) { // Event Handler
// Do something interesting when the button is clicked
}
...
}
Recall: “implements” an interface = takes up a role in Java
25
Approach 3
If you want to further simplify…

protected void onCreate(Bundle savedValues) {


...
// Capture our button from layout
Button button = (Button)findViewById(R.id.interesting);
// Register the onClick listener with the implementation above
button.setOnClickListener(new View.OnClickListener() {
// Event Listener Definition + Registration
public void onClick(View v) { // Event Handler
// Do something interesting when the button is clicked
}
};
...
}

26
Simple Hello World Example in
Xcode with MVC Design Pattern

When “Click Me” button is


pressed, “Hello World !!!” will
be changed into “Hello iOS!!!”.

Note: MVC is the default


design pattern in Xcode.

27
Simple Hello World Example in Xcode
with MVC Design Pattern (View)
In Xcode, we can build the user interface (called View)
using tools provided in Interface Builder.

28
Simple Hello World Example in Xcode
with MVC Design Pattern (Controller)
• In Xcode, Model (program logic) is defined within a Controller file.
• We can link up View and Controller by Ctrl-Drag.

Ctrl Drag

We will be asked to enter a


name for the Label. For
simplicity, just name it as
“label1”.

29
Simple Hello World Example in Xcode
with MVC Design Pattern (Controller)
• In Xcode, Model (program logic) is defined within a Controller file.
• We can link up View and Controller by Ctrl-Drag.

Ctrl Drag

• Choose “Touch Up Inside” for “Event”


• We will be asked to enter a name for the Button.
For simplicity, just name it as “button1”.

30
Simple Hello World Example in Xcode
with MVC Design Pattern (Controller)
Controller program in Swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBAction func button1(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

31
Simple Hello World Example in
Xcode with MVC Design Pattern

Link up UI and
program logic

- Accept button click Update label


- Display labels content

32
Chapter 4.

End

2020-2021
COMP3330 Interactive Mobile Application Design and Programming
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong

You might also like