Sie sind auf Seite 1von 20

1,.

INTRODUCTION In this section, I illustrate the process of object-oriented design by developing an example design for the control software that is embedded in an automated weather station. As I discussed in the introduction, there are several methods of object-oriented design with no definitive best method or design process. The process that I cover here is a general one that incorporates activities that are common to most OOD processes. In this respect, it is comparable to the proposed UML process but I have significantly simplified this process for presentation here.The general process that I use here for object-oriented design has a number of stages: 1. Understand and define the context and the modes of use of the system 2. Design the system architecture 3. Identify the principal objects in the system 4. Develop design models 5. Specify object interfaces I have deliberately not illustrated this as a simple process diagram as that would imply that there was a neat sequence of activities in this process. In fact, all of the above activities can be thought of as inter-leaved activities that influence each other. Objects are identified and the interfaces fully or partially specified as the architecture of the system is defined. As object models are produced, these individual object definitions may be refined and this may mean changes to the system architecture. I discuss these as separate stages in the design process later in this section. However, you should not assume from this that design is a simple, well-structured process. In reality, you develop a design by proposing solutions and refining these solutions as information becomes available. You inevitably have to backtrack and retry when problems arise. Sometimes you explore options in detail to see if they work; at other times you ignore details until late in the process. And also I illustrate these process activities by developing an example of an object-oriented design. The example that I use to illustrate object-oriented design is part of a system for creating weather maps using automatically collected meteorological data. 2. LAB EXERCISES

2.1 Lab Exercise 1

Here in this object-oriented design process, we were asked to identify classes, their responsibilities (methods), and relationship between them. And also we were given the following case study which we had to implement on our own with the current knowledge of object-oriented design process. In this program they have given that AIT bookstore sells books, newspapers, and souvenirs to customers. In each book it has a title, author(s), ISBN number, publisher, and price. And a newspaper has a name, language, and price. A souvenir has a price and type (showpiece, wearable etc). AIT bookstore has walk-in customers as well as online customers (require shipment on a specific address). And our responsibility is to provide an object-oriented design for their sales system. Step 1 Discover classes and draw CRC cards. The following classes are include in my solution is as given below. Book Newspaper Souvenir Control Unit Walk in Online customer What is a CRC card ? CRC stands for Class, Responsibilities, and Collaborators A useful and popular technique for OO paradigm an index card annotated in a group setting to represent a class of objects, its behavior, and its interactions

created in informal brainstorming sessions, wherein functions of the applications to be modeled are simulated and the outcome is recorded on the cards.

CRC cards (Class-Responsibility-Collaborator cards). CRC cards are a \laboratory" for collaborative development and exploration of an object-oriented analysis. Traditionally, CRC cards are simply 3x5 index cards, one for each class being considered in a design, annotated with two columns: One for the responsibilities of that class, and the other with the collaborators that the class will need to complete the responsibilities. CRC cards are popular in our course: We learnt CRC cards as one part of a design process that begins with brainstorming class names and developing. Blank CRC Card

Responsibilities - An action that an implementation of an object must be capable of performing Collaboration - An interaction between objects in which one object requests that another object carry out one of its responsibilities

CONTROL UNIT

none none none none none

none none none none

SOUVENIER

none none none none

Step 2 Provide a UML diagram that shows relationships between classes. UML (Unified Modelling Language) Several different notations for describing object-oriented designs were proposed in the 1980s and 1990s. The Unified Modeling Language is an integration of these notations. It describes notations for a number of different models that may be produced during OO analysis and design. It is now a de facto standard for OO modelling.

Arrows which we use to represent the process

Examples to understand the process:

The UML diagram for the required program will be as follows:

Control Unit

Book Store

Case Study: Printing an Invoice In this exercise we were asked to retype the codes given in the text and compile and run the program. Books getTitle() getAuthor() getISBNumber() getPrice() getPublisher()

Methods

News Papers getName() getLanguage() getPrice() Souvenir getType() getPrice() Control Unit getName() getAddress()

Methods

Methods

Methods

Online Customers getName() getAddress() getPaymentDetails() getDeliveryDetails() Walk in customers getName() getAddress() getPaymentMethod()

Methods

Methods

AITBookStore getDetails() getDescription() buyBooks() buyNewspapers() buySouvenirs() getTotalSales() getTotalProducts()

Methods

Codes for Product class


public class Product { /** Constructs a product from a description and a price. @param aDescription the product description @param aPrice the product price */ public Product(String aDescription, double aPrice) { description = aDescription; price = aPrice; } /** Gets the product description. @return the description */ public String getDescription() { return description; } /** Gets the product price. @return the unit price */ public double getPrice() { return price; } private String description; private double price;

Codes for LineItem class


public class LineItem { /** Constructs an item from the product and quantity. @param aProduct the product @param aQuantity the item quantity */ public LineItem(Product aProduct, int aQuantity) { theProduct = aProduct;

quantity = aQuantity;

/** Computes the total cost of this line item. @return the total price */ public double getTotalPrice() { return theProduct.getPrice() * quantity; } /** Formats this item. @return a formatted string of this line item */ public String format() { return String.format("%-0s%8.2f%5d %8.2f",theProduct.getDescription(), theProduct.getPrice(),quantity, getTotalPrice()); } private int quantity; private Product theProduct;

Codes for Address class


public class Address { /** Constructs a mailing address. @param aName the recipient name @param aStreet the street @param aCity the city @param aState the two-letter state code @param aZip the ZIP postal code */ public Address(String aName, String aStreet,String aCity, String aState, String aZip) { name = aName; street = aStreet; city = aCity; state = aState; zip = aZip; } /** Formats the address. @return the address as a string with three lines */

public String format() { return name + "\n" + street + "\n"+ city + ", " zip; } private String name;

+ state + " " +

private private private private }

String String String String

street; city; state; zip;

Codes for Invoice class


import java.util.ArrayList; public class Invoice { /** Constructs an invoice. @param anAddress the billing address */ public Invoice(Address anAddress) { items = new ArrayList<LineItem>(); billingAddress = anAddress; } /** Adds a charge for a product to this invoice. @param aProduct the product that the customer ordered @param quantity the quantity of the product */ public void add(Product aProduct, int quantity) { LineItem anItem = new LineItem(aProduct, quantity); items.add(anItem); } /** Formats the invoice. @return the formatted invoice */ public String format() { String r = " I N V O I C E\n\n"+ billingAddress.format() + String. format("\n\n%-30s%8s%5s%8s\n","Description", "Price", Qty", "Total"); for (LineItem i : items) { r = r + i.format() + "\n"; } r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue()); return r; } /** Computes the total amount due. @return the amount due */ public double getAmountDue() { double amountDue = 0; for (LineItem i : items) { amountDue = amountDue + i.getTotalPrice(); } return amountDue;

} private Address billingAddress; private ArrayList<LineItem> items; }

Codes for the InvoicePrinter class


public class InvoicePrinter { public static void main(String[] args) { Address samsAddress = new Address("Sam's Small Appliances","100 Main Street", "Anytown", "CA", "98765"); Invoice samsInvoice samsInvoice.add(new samsInvoice.add(new samsInvoice.add(new = new Invoice(samsAddress); Product("Toaster", 29.95), 3); Product("Hair dryer", 24.95), 1); Product("Car vacuum", 19.99), 2);

System.out.println(samsInvoice.format()); } }

Out put :

Is it a good design decision to remove Address class and use a String field in the Invoice class as a address? No. In this lab exercise even though it is also possible, it is not supported by the basic rule of cohesion in Object oriented programming. Cohesion says that a single class should have a single concept. Therefore, whenever we observe two concepts within the same class, we should always try to introduce a new class.
Technically, if we have the address as field inside the Invoice class, we would need to change the class definition whenever we need to change our address. We cannot produce two invoices having

different addresses, without changing the class definition. But, by using a separate class, we can create any number of addresses, and also indefinite number of invoices with different addresses, without altering the definition of the Invoice class.

Is it possible to introduce inheritance?


Yes we can define several products and they can inherit the functions of the product so that we have classes for each and every product and all of them are under the product class.
Does it make sense to rename the class Product as LineItemDetail?

No, it does not make sense to rename the product class as LineItemDetail. If we rename it that way, the class would be more specific to the LineItem alone and lose its reusability. Also the LineItem details are more like instances of the LineItem class rather than separate classes..

3. In Lab Exercises

Exercise P12.1 on page 580 In this exercise I was asked to enhance the invoice-printing program by providing for two kinds of line items: One kind describes products that are purchased in certain numerical quantities (such as3 toasters), another describes a fixed charge (such as shipping: $5.00). I modified the Invoice Printer program to accept two types of LineItems, Products and FixedPriceItems. For this I made the Products and FixedPriceItems subclasses of the LineItems class while the LineItems class, I made it an abstract class with only abstract methods that were overwritten by its subclasses. And in the line item class I improved its format method so that if the instance or the object of the purchase object was fixed price then the format of the invoice would be different. In the invoice class I add another add method so that input without a quantity would be supported. I edited the codes in the Invoice class accordingly and used the InvoicePrinter from the text. The codes are as given below.

Codes for the purchase class


/** Describes a purchase with a description and a price. */ public class Purchases { /** Constructs a purchase from a description and a price. @param aDescription the purchase description @param aPrice the purchase price */ public Purchases(String aDescription, double aPrice) { description = aDescription; price = aPrice; } /**

Gets the purchase description. @return the description */ public String getDescription() { return description; } /** Gets the purchase price. */ public double getPrice() { return price; } private String description; private double price; }

Code for product class


/** Describes a product with a description and a price. */ public class Product extends Purchases//makes a product with the inheritance of the purchase { /** Constructs a product from a description and a price. @param aDescription the product description @param aPrice the product price */ public Product(String aDescription, double aPrice) { super(aDescription,aPrice);//the purchase is initiated } }

Codes for fixedpriceitem class


public class FixedPriceItem extends Purchases{//this is for fixed charges public FixedPriceItem(String aDescription, double aPrice) { super(aDescription, aPrice);//initiates the super class } }

Codes for lineitem class


/** Describes a quantity of an article to purchase. */ public class LineItem { /** Constructs an item from the product and quantity.

@param aProduct the product @param aQuantity the item quantity */ public LineItem(Purchases aProduct, int aQuantity) { theProduct = aProduct; quantity = aQuantity; } /** Computes the total cost of this line item. @return the total price */ public double getTotalPrice() { return theProduct.getPrice() * quantity; } /** Formats this item. @return a formatted string of this line item */ Public String format() { if(theProduct instanceof Product){//checks whether the purchase is a product or not return String.format("%-30s%8.2f%5d%8.2f", theProduct.getDescription(), theProduct.getPrice(), quantity, getTotalPrice()); } else return String.format("%-30s%8.2f%5s%8.2f",//the f for float is changed to s(String) so that the dash can be stored theProduct.getDescription(), theProduct.getPrice(), "-", getTotalPrice()); } private int quantity; private Purchases theProduct; }

Codes for invoice class


import java.util.ArrayList; /** Describes an invoice for a set of purchased products. */ public class Invoice { /** Constructs an invoice. @param anAddress the billing address */ public Invoice(Address anAddress) { items = new ArrayList<LineItem>(); billingAddress = anAddress; }

/** Adds a charge for a product to this invoice. @param aProduct the product that the customer ordered @param quantity the quantity of the product */ public void add(Purchases aProduct, int quantity) { LineItem anItem = new LineItem(aProduct, quantity); items.add(anItem); } public void add(Purchases item)//the add method for the fixed charges { LineItem anItem = new LineItem(item,1); items.add(anItem); } /** Formats the invoice. @return the formatted invoice */ public String format() { String r = " I N V O I C E\n\n"+ billingAddress.format()+ String. format("\n\n%-30s%8s%5s%8s\n", "Description", "Price", "Qty", "Total"); for (LineItem i : items) { r = r + i.format() + "\n"; } r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue()); return r; } /** Computes the total amount due. @return the amount due */ public double getAmountDue() { double amountDue = 0; for (LineItem i : items) { amountDue = amountDue + i.getTotalPrice(); } return amountDue; } private Address billingAddress; private ArrayList<LineItem> items; }

Codes for tester class


/** This program demonstrates the invoice classes by printing a sample invoice. */ public class InvoicePrinter {

public static void main(String[] args) { Address samsAddress= new Address("Sam's Small Appliances","100 Main Street", "Anytown", "CA", "98765"); Invoice samsInvoice = new Invoice(samsAddress); samsInvoice.add(new Product("Toaster", 29.95), 3); samsInvoice.add(new Product("Hair dryer", 24.95), 1); samsInvoice.add(new Product("Car vacuum", 19.99), 2); samsInvoice.add(new FixedPriceItem("Rush charge", 20.00));//the added fixed charge System.out.println(samsInvoice.format()); } }

Out put:

Exercise P12.2 on page 580 In the following exercise I improved the above invoice printer so that the width of the columns can be given as an input via an int array. By this means the width can be entered as for the users need unlike in the previous program where the width of the column was defined in the program and also I used the number format class and to get the required dollar signs I used the locale class. Number Format Classes the NumberFormat class from the library to format the strings instead of the given format since the currency values would not look nice if the entered values had too many decimals and so on. NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are. The amended codes and the relevant output are given below.
/** Describes a mailing address. */ public class Address { /** Constructs a mailing address.

@param @param @param @param @param */ public String {

aName the recipient name aStreet the street aCity the city aState the two-letter state code aZip the ZIP postal code Address(String aName, String aStreet, aCity, String aState, String aZip) name = aName; street = aStreet; city = aCity; state = aState; zip = aZip;

} /** Formats the address. @return the address as a string with three lines */ public String format() { return name + "\n" + street + "\n"+ city + ", " + state + " " + zip; } private String name; private String street; private String city; private String state; private String zip; }

In the program they have used a separate Address class instead of adding it as an instant of the Invoice class. Its because address is an important fact when printing an invoice. The things should be delivered to the correct place. Codes of the Product class
/** Describes a product with a description and a price. */ public class Product { /** Constructs a product from a description and a price. @param aDescription the product description @param aPrice the product price */ public Product(String aDescription, double aPrice) { description = aDescription; price = aPrice; } /** Gets the product description. @return the description */ public String getDescription() { return description; } /** Gets the product price. @return the unit price */ public double getPrice() { return price; }

private String description; private double price; }

This class holds the detail about the product, which is being sold. Codes of the LineItem class
/** Describes a quantity of an article to purchase. */ public class LineItem { /** Constructs an item from the product and quantity. @param aProduct the product @param aQuantity the item quantity */ public LineItem(Product aProduct, int aQuantity) { theProduct = aProduct; quantity = aQuantity; } /** Computes the total cost of this line item. @return the total price */ public double getTotalPrice() { return theProduct.getPrice() * quantity; } /** formats this item. @return a formatted string of this line item */ public String format() { return String.format("%-30s%8.2f%5d%8.2f", theProduct.getDescription(), theProduct.getPrice(), quantity, getTotalPrice()); } private int quantity; private Product theProduct; }

LineItem class computes the total price of an item in certain quantities and arranges the line to be printed in the invoice. This uses a string format method to arrange the line. Codes for Invoice class
import java.util.ArrayList; /** Describes an invoice for a set of purchased products. */ public class Invoice { /** Constructs an invoice. @param anAddress the billing address */ public Invoice(Address anAddress) { items = new ArrayList<LineItem>(); billingAddress = anAddress; } /** Adds a charge for a product to this invoice.

@param aProduct the product that the customer ordered @param quantity the quantity of the product */ public void add(Product aProduct, int quantity) { LineItem anItem = new LineItem(aProduct, quantity); items.add(anItem); } /** Formats the invoice. @return the formatted invoice */ public String format() { String r = " I N V O I C E\n\n" + billingAddress.format() + String. format("\n\n%-30s%8s%5s%8s\n", "Description", "Price", "Qty", "Total"); for (LineItem i : items) { r = r + i.format() + "\n"; } r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue()); return r; } /** Computes the total amount due. @return the amount due */ public double getAmountDue() { double amountDue = 0; for (LineItem i : items) { amountDue = amountDue + i.getTotalPrice(); } return amountDue; } private Address billingAddress; private ArrayList<LineItem> items; }

Invoice class arranges all the strings together to print the invoice and calculates the total amount to be paid. Codes of the InvoicePrinter class
/** This program demonstrates the invoice classes by printing a sample invoice. */ public class InvoicePrinter { public static void main(String[] args) { Address samsAddress = new Address("Sam's Small Appliances", "100 Main Street", "Anytown", "CA", "98765"); Invoice samsInvoice samsInvoice.add(new samsInvoice.add(new samsInvoice.add(new = new Invoice(samsAddress); Product("Toaster", 29.95), 3); Product("Hair dryer", 24.95), 1); Product("Car vacuum", 19.99), 2);

System.out.println(samsInvoice.format()); } }

Out Put :

4. Home Work Exercises


4.1 Home Work Exercise 1
What relationship is appropriate between the following classes: aggregation, inheritance, or neither? (a) UniversityStudent (c) StudentFreshman (d) StudentProfessor (e) CarDoor (f) TruckVehicle (g) TrafficTrafficSign (h) TrafficSignColor : : : : : : : aggregation neither inheritance netiher aggregation inheritance aggregation aggregation

(b) StudentTeachingAssistant:

4.2 Home Work Exercise 2

Draw a UML diagram for the Coin and CashRegister classes

Before introduce Measureable interface cash register class depends on the coin class. Actually these two class has an aggregation relationship.
CashRegister Coin

4. CONCLUSION From these lab exercises I learnt on how to provide an object oriented solution to real life problems. One key issue was to be able to decide the suitable classes and their responsibilities (methods). This was simply implemented by the usage of CRC (classes, responsibilities and collaborators) cards. Afterwards to identify the relationships between classes. To be able to justify whether the necessity lied to implement any interfaces, inheritance and also aggregations. I further enhanced my knowledge programming and gained a lot more tips on how to format String objects and Numbers. I also used the concepts of Cohesion and Coupling to produce more generalised and reusable solutions that are more demanding. I learnt the types of relationships between classes that can be present and learnt how to draw UML diagrams representing these relationships. How classes should behave and what classes are suitable and what are the responsibilities, can these classes achieve it without help of other classes if they need any help how they use them and what are the relationships they should build between them likewise concert of the individual programming has been built up.I also learnt a handful of useful methods when it comes to formatting string and numerical output using Number Format class 5. REFERENCES
http://www.javabeginner.com/learn-java/java-abstract-class-and-interface

http://www.selectorweb.com/design_patterns.html
http://www.ibm.com/developerworks/java/library/j-jmod0508/ Inc, A. ( 2003). Class Responsibility Collaborator (CRC) Models. Retrieved from agilemodeling: http://www.agilemodeling.com/artifacts/crcModel.htm java, S. (n.d.). Class NumberFormat. Retrieved from Oracle: http://www.agilemodeling.com/artifacts/crcModel.htm

Das könnte Ihnen auch gefallen