SSD3U2S3
SSD3U2S3
Design
Object-Oriented Programme 1
Unit 2. Class Implementation
2.1 Implementing Classes
2.2 Collections
2.3 Advanced Class Design
Assessments
Exam 2
Object-Oriented Programme 2
2.3 Advanced Class Design
2.3.1 Abstract Classes
2.3.2 Polymorphism
2.3.3 Interfaces
2.3.4 Design Patterns
2.3.5 Singleton Pattern
2.3.6 Strategy Pattern
Assessments
PracticalQuiz 8
Multiple-Choice Quiz 5
Exercise 5
Object-Oriented Programme 3
2.3.1 Abstract Classes
An abstract method consists of a method signature without a
method body. 抽象方法 ,
空方法是抽象方法吗 ?
A method is declared abstract by adding the keyword abstract
to the method signature.
public abstract void eat(int amount);
public abstract void sleep(int hours);
An abstract method must be declared in an abstract class. An
abstract class is denoted by using the abstract modifier.
public abstract class className {
...
}
Object-Oriented Programme 4
note
No instance of an abstract class can be created.
If a subclass of an abstract class does not implement
all abstract methods inherited from its parent,
the subclass must also be defined as abstract.
An abstract class has one purpose
act as the superclass of a class hierarchy.
Object-Oriented Programme 5
example
wagons
tanks
Object-Oriented Programme 6
Change in the UML class notation
In a UML class diagram, the names of abstract
classes and methods are italicized.
Container is an abstract class that defines the abstract
method computeVolume().
Object-Oriented Programme 7
note
Container.java Wagon.java Tank.java
Code explain
In line 7, the class Container is declared using the
modifier abstract.
In line 14, the method computeVolume() is declared
using the modifier abstract.
Class Wagon extends class Container, adding the
attributes width, height, and length
Class Tank extends class Container, adding the
attributes length and radius
Object-Oriented Programme 8
concrete classes
Classesthat are not abstract are called concrete
classes. 具体类
Wagon and Tank are concrete classes.
Object-Oriented Programme 9
An abstract class does not have to have abstract
methods
是不是由其中抽象方法的个数判断一个类为抽象类 ?
You can define a class using abstract to prevent it
from being instantiated
such a class cannot be instantiated because it is
defined as abstract.
In designing some class hierarchies,
only the subclasses can be instantiated;
the superclass is defined as abstract so it cannot be
instantiated
Object-Oriented Programme 10
sample
Object-Oriented Programme 11
note
Class Person is defined as abstract but it does not
contain any abstract methods.
Class Person contains the attribute name and the
method getName().
Class Employee extends class Person, adding the
attribute age and the method getAge().
Class Client extends class Person, adding the
attribute credit and the method getCredit().
Object-Oriented Programme 12
note
No instances of class Person can be created because
Person is abstract.
Consequentially, the following declaration is illegal.
Object-Oriented Programme 13
2.3.2 Polymorphism 多态
A reference variable in Java can hold a reference to
an object of the declared type or
an object of any subtype of the declared type.
Object-Oriented Programme 14
polymorphism
A reference variable of type Container can hold a
reference to an instance of class Wagon or class Tank:
Container container;
container = new Wagon(1, 1, 3);
container = new Tank(1, 3);
This characteristic of a reference variable — being
able to refer to objects of different classes
makes polymorphism possible.
Object-Oriented Programme 15
Polymorphism
Polymorphism allows
one method name to be associated with many
implementations.
When a polymorphic method is called, the JVM
determines which version of the method to execute by
examining the reference variable used in the method
call.
Object-Oriented Programme 16
sample
double volume = container.computeVolume();
would invoke Wagon's computeVolume method when
the reference container refers to an object of class
Wagon, and Tank's computeVolume method when the
reference container refers to an object of class Tank.
Object-Oriented Programme 17
Sample code
Sample code (ContainerDemo.java)
the statement
Object-Oriented Programme 18
2.3.3 Interfaces
Interfaces
UML Representation of Interfaces
Using Interfaces
Comparing Abstract Classes and Interfaces
Object-Oriented Programme 19
Interfaces 接口
In Java an interface defines a set of abstract methods
注意 , 只有抽象方法
some interfaces also include constant declarations
An interface using the keyword interface instead of the
keyword class.
much the same way as a class
public interface MyInterface {
int CONSTANT = 10;
void methodOne();
double methodTwo();
void methodThree(double value);
}
Object-Oriented Programme 20
note
InJava interfaces:
All methods in an interface are implicitly public and
abstract.
the modifiers public and abstract are not used in an
interface definition.
All data fields in an interface are implicitly public,
static, and final.
the modifiers public, static, and final are not used in an
interface definition.
其实 , 接口就是暴露给外部对象的 , 继承或使用 , 所
以都是 public
Object-Oriented Programme 21
using an interface
For a class to make use of an interface, the keyword
implements is used, followed by the name of the interface:
public class ClassA implements MyInterface {
public void methodOne() {
...
}
public double methodTwo() {
...
}
public void methodThree(double value) {
...
}
...
}
Object-Oriented Programme 22
implements an interface
When a class implements an interface,
it must implement all methods in the interface.
If the class does not implement all the methods, the
class must be defined as abstract.
An interface can extend another interface.
the parent interface is called the superinterface,
similar to the term superclass for parent classes.
The child interface is called the subinterface, similar
to the term subclass for child classes.
public interface MyInterface extends InterfaceOne {
void aMethod();
}
Object-Oriented Programme 23
an interface can extend any number of
interfaces
A class can only extend one class.
An interface can extend any number of interfaces:
public interface MyInterface extends Interface1, Interface2 {
void aMethod();
}
A class can implement many interfaces
public class ClassA implements
Interface1, Interface2, Interface3 {
...
Object-Oriented Programme 24
UML Representation of Interfaces
Object-Oriented Programme 25
UML Representation of Interfaces
An interface is represented in UML by a rectangle with 2
compartments.
The first compartment contains
the heading <<interface>>
the name of the interface
The second compartment describes
the methods of the interface.
In UML, interfaces lack attributes; they only have operations.
Classes that implement an interface are indicated in UML by a
dashed line between the class and the interface with a triangle
next to the interface
classes ClassA and ClassB implement the methods declared
in the interface MyInterface.
Object-Oriented Programme 26
sample
In the figure,
InterfaceTwo extends
InterfaceOne, and
ClassA implements
InterfaceTwo and
InterfaceThree
ClassA must implement
all methods declared in
InterfaceOne,
InterfaceTwo, and
InterfaceThree.
Object-Oriented Programme 27
Using Interfaces
Object-Oriented Programme 28
Sample code
Device.java
DeviceDemo.java
Object-Oriented Programme 29
note
All classes that implement the interface Device must implement
the methods turnOff() and turnOn().
DeviceDemo implements the interface Device.
Class DeviceDemo has one attribute, the name of the
device.
The methods turnOff() and turnOn() in class DeviceDemo
display a message in the standard output.
Class Stopwatch also implements the interface Device.
When the stopwatch is turned on, the method turnOn
assigns the current time, in milliseconds, to the instance
variable startTime.
When the stopwatch is turned off, the method turnOff
outputs the how long, in milliseconds, the stopwatch has
been turned on. Object-Oriented Programme 30
Comparing Abstract Classes and Interfaces
There are significant differences between abstract classes and
interfaces:
interface abstract class
cannot define instance variables can define instance variables
Object-Oriented Programme 31
note
An abstract class should be used when some implementation
details, like variables and method definitions, are common to all
classes in a hierarchy.
the abstract class would be the root of the class hierarchy.
An interface should be used to define a behavior that must be
implemented by classes in different hierarchies.
Interfaces get the power of polymorphism because
an interface defines a type.
This makes it possible for classes belonging to different
hierarchies to be treated as instances of the same type.
实现同一接口的子类都是相同类型 !
Object-Oriented Programme 32
2.3.4 Design Patterns
Design patterns describe practical solutions to common design
problems that occur repeatedly in software development.
一种高层次的软件复用
软件代码
组件 (API, 动态链接库 DLL)
设计思想及解决方案
A design pattern description consists of:
A name that identifies the pattern
A description of the problem that the pattern addresses
A description of the solution that includes the class
structures that solve the problem
A discussion of the consequences of using the pattern
Object-Oriented Programme 33
Good illustrations of object-oriented concepts
Design patterns document good design solutions that can
be used for similar problems
form a shared vocabulary( 特定的语汇 , 便于交流理解 ) for
problem-solving discussions.
In addition, design patterns are good illustrations of object-
oriented concepts.
Design patterns were popularized by the book Design Patterns:
Elements of Reusable Object-Oriented Software
by Erich Gamma, Richard Helm, Ralph Johnson, and John
Vlissides. ( 四人帮 )
covers 23 patterns, grouped into three categories
Object-Oriented Programme 34
23 patterns
Creational Patterns: ▪Abstract Factory ▪Builder
▪Factory Method
▪Prototype ▪Singleton
Structural Patterns: ▪Adapter ▪Bridge
▪Composite ▪Decorator
▪Façade ▪Flyweight ▪Proxy
Behavioral Patterns: ▪Chain of Responsibility
▪Command ▪Iterator ▪Mediator
▪Memento ▪Observer ▪State
▪Strategy ▪Visitor ▪Interpreter
▪Template Method
Object-Oriented Programme 35
2.3.5 Singleton Pattern 单个模式
Description
Structure
Example
Consequences
Object-Oriented Programme 36
Description
In some applications, there are classes that should
only be instantiated once.
an operating system should have only one system
clock and a company should have only one
accounting system.
The singleton pattern ensures that
only one instance of a class is created and
provides a method to access that one instance.
Every object that uses an instance of a singleton
class uses the same instance.
Object-Oriented Programme 37
Structure
the static members of the class are underlined.
The static attribute instance contains the single
instance of the class.
The constructor is defined as private so that other
classes cannot create instances.
The static method getSingletonInstance() returns
the single instance of the class.
The first time this method is called, it creates the
single instance.
Object-Oriented Programme 38
Example
Class ICarnegieInfo contains the contact information
for iCarnegie.
Sample code (ICarnegieInfo.java)
Only one instance of class ICarnegieInfo can be
created.
Object-Oriented Programme 39
note
line 10
the private static variable singletonInstance is initialized with
an instance of class ICarnegieInfo —singletonInstance will
be the only instance of class ICarnegieInfo in an application.
line 22
the constructor is defined as private so other classes cannot
create instances of ICarnegieInfo.
line 36
the class defines a static method called
getSingletonInstance that returns a reference to the single
instance of ICarnegieInfo.
The first call to getSingletonInstance creates the single
instance.
Object-Oriented Programme 40
Sample code
ICarnegieInfoDemo.java
Inlines 22 and 23
the application obtains the single instance by calling
the static method
ICarnegieInfo.getSingletonInstance.
Object-Oriented Programme 41
Consequences
The singleton pattern has the following benefits:
A singleton class can control how and when client
code accesses the single instance.
Client code
does not have the freedom to use the new operator to
create an instance of the singleton class.
it must call a static method that returns a reference to the
single instance.
A singletonclass can be easily modified if
requirements change and the application needs to
limit the number of instances to a number other
than one. 对于固定个数实例的应用场合都试用
Object-Oriented Programme 42
2.3.6 Strategy Pattern 策略 模式
Introduction
Description
UML Class Diagram
Example
Interface BorrowersFormatter
Class PlainTextBorrowersFormatter
Class HTMLBorrowersFormatter
Class XMLBorrowersFormatter
Class LibrarySystem
Complete System
Object-Oriented Programme 43
Introduction
The strategy pattern is more difficult to understand
than the singleton pattern
it uses interfaces and polymorphism.
Object-Oriented Programme 44
Example for understand the pattren
Consider an e-commerce system that supports sales in the
United States, Mexico, and Canada.
In the near future, the customer base may expand to include
countries in South America.
The system must know how to calculate the sales tax for
customers in three countries,
each of which has its own rules for calculating sales tax.
The design of the code for sales-tax calculation should be
flexible so it will be easy to add other countries.
One solution is a monolithic method calculateTax() that
calculates the sales taxes for every country.
This method would be part of the class that modeled an
order.
Object-Oriented Programme 45
Sample code (Order.java)
public class Order {
/** Calculates the tax of an order.
* @param country The country that will tax the order.
* @param amount The cost of the order.
* @return the tax amount
*/
private double calculateTax(String country, double amount) {
double tax
if (country.equals("United States")) {
tax = ... ;
} else if (country.equals("Canada")) {
tax = ... ;
} else if (country.equals("Mexico")) {
tax = ... ;
}
...
return tax;
} 46
Object-Oriented Programme
}
Drawbacks of the the Order class Implements
This solution has some drawbacks:
If the rules to calculate the sales tax are complex,
the method calculateTax will be long and complex.
One class contains 都在一个类中实现
the code that uses calculateTax and
the code that implements calculateTax
Object-Oriented Programme 47
Another solution
A solution that uses the strategy pattern doesn't have
these drawbacks.
In a strategy-pattern solution,
the code to calculate the sales tax for the United
States is encapsulated in its own class,
as is the code for Canada and Mexico.
Each class implements its own version of the
calculateTax().
Object-Oriented Programme 48
Another solution
The logical relationship between the three classes is
expressed in the following class diagram
Object-Oriented Programme 49
note
The interface TaxCalculator declares the method calculateTax.
The classes that implement the interface TaxCalculator agree to
define the method calculateTax.
The complexity of the sales-tax code is reduced by separating it
into three classes.
If a country is added to the system, a new class that
encapsulates the sales-tax rules for that country is created.
The new class implements the interface TaxCalculator and
defines its own version of the method calculateTax.
前面一种方案要修改方法代码 , 经常会带入错误
Object-Oriented Programme 50
Description
The book Design Patterns describes the strategy pattern in the
following words:
"Define a family of algorithms, encapsulate each one, and
make them interchangeable. Strategy lets the algorithm vary
independently from the clients that use it."
In the strategy pattern, each algorithm is encapsulated in its
own class.
An interface that declares a method for executing an
algorithm is created
all the algorithm classes implement the interface.
Consequently, each algorithm class has its own version of the
method.
When the need for a particular algorithm arises, the version
of the method associated with that algorithm is invoked.
Object-Oriented Programme 51
An algorithm can be considered a strategy
Applications where the strategy pattern may prove
useful include:
An application for compressing files that allows the
user to select the type of compression
An application where the nature of the data to be
sorted determines the sorting algorithm
An algorithm can be considered a strategy and hence
the origin of the pattern's name.
strategy pattern
Object-Oriented Programme 52
UML Class Diagram
Object-Oriented Programme 53
Notes of strategy pattern
The interface Strategy defines the signature of the method ( 方
法签署 = 方法名 + 参数列表 + 返回值类型 ) that will be used to
invoke an algorithm.
Classes ConcreteStrategyX implement the method declared in
the interface Strategy.
The class Context maintains a reference, called strategy, to an
object of type Strategy.
The class Context contains setStrategy()
allows client code to specify the desired algorithm.
setStrategy() takes an input parameter of type Strategy so
the client code must pass it an instance of the
ConcreteStrategy class associated with the desired
algorithm.
setStrategy() updates the reference variable strategy.
Object-Oriented Programme 54
Notes of strategy pattern
The class Context contains invokeStrategy(),
which the client code calls when it needs to execute
an algorithm.
The algorithm used is determined by the reference
variable strategy,
which refers to an instance of a ConcreteStrategy
class.
Object-Oriented Programme 55
Example
The following class diagram shows an enhancement
to the library system.
This enhancement makes it possible to format the
information in the borrower database in one of three
ways: plain text, HTML, and XML
Object-Oriented Programme 56
Object-Oriented Programme 57
In the library system
Interface BorrowersFormatter is the strategy interface
that declares a method formatBorrowers() that
produces a string representation of the borrower
database.
Class PlainTextBorrowersFormatter implements
formatBorrowers. Its version of the method renders
the information in the borrower database in a plain text
format.
Class HTMLBorrowersFormatter implements
formatBorrowers. Its version of the method renders
the information in the borrower database in an HTML
format.
Object-Oriented Programme 58
In the library system
Class XMLBorrowersFormatter implements
formatBorrowers. Its version of the method renders
the information in the borrower database in an XML
format.
Class LibrarySystem is the context class. It also
contains the client code. The method
setBorrowersFormatter is used to specify the
formatter. The method displayBorrowers is used to
execute the specified formatter: it calls the method
formatBorrowers to display the borrower database in
the specified format.
Object-Oriented Programme 59
Interface BorrowersFormatter
Sample code(BorrowersFormatter.java)
Object-Oriented Programme 60
Class PlainTextBorrowersFormatter
Sample code (PlainTextBorrowersFormatter.java)
Class PlainTextBorrowersFormatter is implemented as
a singleton so a new object will not be created every
time the plain-text format is used:
The constant NEW_LINE, defined in line 19,
contains the line separator as defined by the system
property line.separator.
Not all platforms use the newline character (\n) to
terminate lines.
Windows systems use "\r\n“
Macintosh systems use '\r'.
Object-Oriented Programme 61
Class HTMLBorrowersFormatter
HTMLBorrowersFormatter.java is an implementation
of the concrete class HTMLBorrowersFormatter.
Class HTMLBorrowersFormatter is implemented as a
singleton so a new object will not be created every
time the HTML format is used:
Object-Oriented Programme 62
Class XMLBorrowersFormatter
XMLBorrowersFormatter.java is an implementation of
the concrete class XMLBorrowersFormatter.
Class XMLBorrowersFormatter is implemented as
singleton so a new object will not be created every
time the XML format is used:
Object-Oriented Programme 63
Class LibrarySystem
LibrarySystem.java is an implementation of the class
LibrarySystem.
Class LibrarySystem lets the user specify a format and then
display the information in the borrower database in the
specified format.
The class contains the following elements:
A reference variable of type BorrowersFormatter that refers
to the current format
PlainTextBorrowersFormatter,
HMTLBorrowersFormatter, or
XMLBorrowersFormatter object
Object-Oriented Programme 65
Complete System
Thefollowing files implement the other classes in this
version of the library system:
Book.java
Recording.java
CatalogItem.java
Catalog.java
Borrower.java
BorrowedItems.java
BorrowerDatabase.java
Object-Oriented Programme 66