Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to OO Program Design

Similar presentations


Presentation on theme: "Introduction to OO Program Design"— Presentation transcript:

1 Introduction to OO Program Design
Software College of SCU Instructor: Shu Li Review

2 Unit 1 Class Design Basic Console I/O StringTokenizer Exception UML class diagram

3 Console I/O private static BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter stdOut = new PrintWriter(System.out, true); private static PrintWriter stdErr = new PrintWriter(System.err, true); true, autoflush

4 StringTokenizer import java.util.*; StringTokenizer tokenizer = new StringTokenizer(data, "_"); tokenizer.countTokens(); //number of tokens while(tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); } // traverse each token

5 Exception (checked/unchecked)
try { stdErr.print("Enter an integer > "); stdErr.flush(); // print without auto flush return Integer.parseInt(stdIn.readLine()); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); // terminate the program } catch (NumberFormatException nfe) { stdErr.println("Invalid number format"); }

6 UML class diagram (Inheritance/Association)
Solid line: extends Dashed line: implements

7 Unit 2 Class Implementation
equals()/toString() Vector/ArrayList JDK 5 Vector<String> ArrayList<String> For each loop (Iterable interface/iterator method) JUnit Design Pattern

8 Vector and Iterator

9 methods defined in class Vector
Vector(). Constructs an empty collection. int size(). Returns the number of objects in the collection. boolean isEmpty(). Determines if there are no objects in the collection. boolean contains(Object elem). Determines if the specified object is an element of the collection (as determined by the method equals). boolean add(E o). Appends the specified object to the end of the collection. void add(int index, E element). Inserts the specified object at the specified index position, shifting any subsequent elements to the right (adds one to their indices). E get(int index). Returns the object at the specified position. public E set(int index, E element). Replaces the element at the specified index position with the specified object. public boolean remove(Object o). Removes the first occurrence of the specified object (using method equals), shifting any subsequent elements to the left (subtracts one from their indices). E remove(int index). Returns the object at the specified position after first removing it from the collection and shifting any subsequent elements to the left (subtracts one from their indices).

10 Methods Defined in Class ArrayList
ArrayList(). Constructs an empty collection. int size(). Returns the number of objects in the collection. boolean isEmpty(). Determines if there are no objects in the collection. boolean contains(Object elem). Determines if the specified object is an element of the collection (as determined by the method equals). boolean add(E o). Appends the specified object to the end of the collection. void add(int index, E element). Inserts the specified object at the specified index position, shifting any subsequent elements to the right (adds one to their indices). E get(int index). Returns the object at the specified position. public E set(int index, E element). Replaces the element at the specified index position with the specified object. public boolean remove(Object o). Removes the first occurrence of the specified object (using method equals), shifting any subsequent elements to the left (subtracts one from their indices). E remove(int index). Returns the object at the specified position after first removing it from the collection and shifting any subsequent elements to the left (subtracts one from their indices).

11 Code Demo See: LibrarySystem import java.util.*; public class Client {
private String name; private Vector accounts; public Client(String initialName) { name = initialName; accounts = new Vector(); } public void addAccount(BankAccount bankAccount) { accounts.add(bankAccount); public Iterator getAccountIterator() { return accounts.iterator(); public int getNumberOfAccounts() { return accounts.size(); See: LibrarySystem

12 JDK 5 public class Client implements Iterable<BankAccount> { … private Vector<BankAccount> accounts; public Client(String initialName) { accounts = new Vector<BankAccount>(); } public Iterator<BankAccount> iterator() { return accounts.iterator(); for (BankAccount account : client) { totalBalance += account.getBalance();

13 Creating a test class in JUnit
Define a subclass of TestCase Override the setUp() method to initialize object(s) under test. Override the tearDown() method to release object(s) under test. Define one or more public testXXX() methods that exercise the object(s) under test and assert expected results.

14 JUnit Methods assertEquals(x, y) – Test passes if x and y are equal
x and y can be primitives or any type with an appropriate equals method Three argument versions exist for floating point numbers assertFalse(b) – Test passes if boolean value b is false assertTrue(b) – Test passes if boolean value b is true assertNull(o) – Test passes if object o is null assertNotNull(o) – Test passes if object o is not null assertSame(ox, oy) – Test passes if ox and oy refer to the same object assertNotSame(ox, oy) – Test passes if ox and oy do not refer to the same object

15 Design Pattern

16 Singleton Pattern Constructor private

17 Strategy Pattern

18 Composite Design Pattern
To allow clients to treat both single components and collections of components identically To define recursive data structures such as trees uses Leaf operation() Component Composite add(Component) remove(Component) * Client 18 18

19 Decorator Pattern

20 Observer Pattern

21 Unit 3Advanced Class Implementation
3.1 Input and Output Programming

22 Abstract Classes InputStream & OutputStream Reader & Writer

23 Line-oriented I/O

24 Design Pattern - Factory Pattern
Creational pattern One of the most used design patterns in Java. Create object without exposing the creation logic to the client and refer to newly created object using a common interface.

25 Factory Pattern - Demo FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.

26 Factory Pattern - Demo 1. create a Shape interface and concrete classes implementing the Shape interface. //Shape.java public interface Shape { void draw(); } //Square.java public class Square implements Shape { public void draw() { System.out.println("Inside Square::draw() method."); } //Rectangle.java public class Rectangle implements Shape { public void draw() { System.out.println("Inside Rectangle::draw() method."); } //Circle.java public class Circle implements Shape { public void draw() { System.out.println("Inside Circle::draw() method."); }

27 Factory Pattern - Demo 2.Create a Factory to generate object of concrete class based on given information. //ShapeFactory.java public class ShapeFactory { //use getShape method to get object of type shape public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null;

28 Factory Pattern - Demo 3. Use the Factory to get object of concrete class by passing an information such as type. public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //get an object of Circle and call its draw method. Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Circle shape1.draw(); //get an object of Rectangle and call its draw method. Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Rectangle shape2.draw(); //get an object of Square and call its draw method. Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of circle shape3.draw(); }

29 Simple Factory 简单工厂模式是类的创建模式,又叫做静态工厂方法模式,是由一个工厂类根据传入的参量决定创建出哪一种产品类的实例,涉及到工厂角色、抽象产品角色以及具体产品角色。 一: 简单工厂类是整个模式的关键所在,包含了必要的逻辑判断,根据给定信息,决定究竟应该创建哪个类的对象。客户端可以免除直接创建产品对象的责任,而仅仅负责消费对象就可以了,这种做法就实现了对职责权利的分割,有利于优化结构。 二:工厂类集中了所有实例的逻辑,违反了高内聚这一原则,它所能创建的类只能是事先考虑好的,如果一旦添加新的类就需要改变工厂类了;同时,当具体产品增多时,可能就会出现工厂类根据不同的条件创建不同实例的需求,这种对条件的判断和对具体产品类型的判断交错在一起,容易产生错误,对系统的维护和扩展也不利。这些都在工厂方法模式中得到改善。

30 Factory Method 一:在工厂方法模式中,核心的工厂类不再负责所有产品的创建,而是将具体创建工作交给子类去完成,这就允许系统在不修改工厂角色的情况下,创建新的产品。 二:工厂方法模式集中封装了对象的创建,在更换对象时,不要做大的改变就可以实现,降低了客户程序与产品对象的耦合,是简单工厂模式的进一步抽象和推广。

31 Abstract Factory 抽象工厂是应对产品族概念的。比如说,每个汽车公司可能要同时生产轿车,货车,客车,那么每一个工厂都要有创建轿车,货车和客车的方法。 应对产品族概念而生,增加新的产品线很容易,但是无法增加新的产品。


Download ppt "Introduction to OO Program Design"

Similar presentations


Ads by Google