SlideShare a Scribd company logo
1 of 15
1
– Implementing the Decorator Design Pattern
(with Strategy Pattern and Factory Class)
)
PROBLEM
You are to design and implement code based on the Decorator
pattern for generating an
appropriate receipt for a customer buying items at a particular
Best Buy store. The general format of a
receipt is as follows:
Basic Receipt
Store Header (store street address, state abbreviation, phone
number, store number)
Date of Sale
Itemized Purchases
Total Sale (without sales tax)
Amount Due (with added sales tax)
Dynamically-Added Items
Tax Computation object (based on state residing in)
Optional Secondary Headers (“Greetings”) to be printed at the
very top of the receipt,
e.g.,
- “Happy Holidays from Best Buy”
- “Summer Sales are Hot at Best Buy”
Relevant Rebate Forms (to be printed at the end of the receipt)
Promotional Coupons (to be printed at the end of the receipt)
e.g., “10% off next purchase of $100 or more” coupon
APPROACH
We will assume that the code is written as part of the software
used by all Best Buy stores around the
country. Therefore, the information in the Store Header will
vary depending on the particular store's
location. In addition, the amount of sales tax (if any) is
determined by the state that the store resides in,
and included in a receipt by use of the Strategy pattern. The
added items to be displayed on each receipt
(i.e.,. greeting secondary header, rebate form or coupon) will be
handled by use of the Decorator pattern.
Finally, the receipt will be constructed by use of the Factory
class pattern.
Basic Receipt
The information for the basic receipt should be stored in a
BasicReceipt object (see below). The instance
variables of a BasicReceipt should contain the date of sale, a
PurchasedItems object, the total sale
(without tax) and amount due (with added tax), each of type
float. In addition, following the Strategy
design pattern, there should be an instance variable of
(interface) type TaxComputation that can
be assigned the appropriate tax computation object (e.g.,
NJTaxComputation) for the state that the
store resides in.
2
Determining Sales Tax
We will implement tax computation classes so that receipts can
be generated for one of five possible
states: Alabama (4%), Delaware (no sales tax), Georgia (4%),
Maryland (6%) and Missouri (4.225%). Note
that a number of states have a “sales tax holidays” in which
certain items are not taxed (e.g., clothers,
computers) in preparation of the new school year. These
holidays normally last for 2-4 days over at
weekend at the end of summer (e.g., the first weekend in
August). Use the information provided in
Wikipedia about states with a tax holiday (here) to implement a
state computation object that would
properly compute the sales tax of a given state, for a certain set
of purchased items, for the current or
any future year. (Note that we will assume that anything
purchased in Best Buy is a computer-related
item.)
Adding Additional Receipt Items
There are a number of different “add on” items that may need to
be printed with the basic receipt.
During particular times of the year, a receipt header may begin
with a special greeting (e.g., “Happy
Holidays from Best Buy”), called a secondary header, to be
added to the top of a receipt. In addition,
rebate forms may be printed at the end of a receipt if a
purchased item has a mail-in rebate. Finally,
coupons may be printed (also at the end of a receipt) if the total
purchase exceeds a certain dollar amount
(e.g., if spend over $100, get a 10% off coupon for the next
visit).
Objects of interface type AddOn are used to store the added
printout for a receipt. The interface has two
methods - applies (which is passed a PurchasedItems object
containing all of the items for the current
receipt), and getLines (which returns the added lines of text to
be printed as a single String with
embedded newline characters). For AddOn objects of type
SecondaryHeader, applies always returns true.
This is because if a SecondaryHeader exists, it is always added
to the (top) of the receipt. Since rebates
only apply to a specific item, method applies returns true if and
only if the particular item is found in
PurchasedItems. A similar approach is taken for adding coupons
to the end of a receipt, except that
coupons apply if and only if the customer has spent over a
certain amount.
We assume that each Best Buy store downloads the current set
of decorator objects each morning.
Configuration File
A configuration file will be read by the program at start up, to
configure the system for the particular store
location, containing the following information: store street
address, state abbreviation, phone number,
and store number.
Factory Class
You must utilize a factory class to properly construct Best Buy
receipts based on the information read
from the configuration file, and the particular items purchased.
A UML class diagram for the design of this program is given
below.
http://en.wikipedia.org/wiki/Sales_tax_holiday
3
4
INTERFACES AND CLASSES TO UTILIZE
Following are the interface and classes to be used in the design
of the program.
Interfaces
public interface Receipt { // type of all receipt components
(i.e., BasicReceipt and receipt decorators)
public void prtReceipt();
}
public interface AddOn { // the type of added info to a
BasicReceipt (e.g., greetings, rebates, coupons)
public boolean applies(PurchasedItems items);
public String getLines();
}
public interface SecondaryHeading { // marker interface, i.e.,
nothing to implement
}
public interface Rebate { // marker interface, i.e., nothing to
implement
}
public interface Coupon { // marker interface, i.e., nothing to
implement
}
Abstract Classes
public abstract class Decorator implements Receipt {
private Receipt trailer;
public Decorator(Receipt r) {
trailer = r;
}
protected void callTrailer() {
trailer.prtReceipt();
}
public abstract void prtReceipt();
}
public abstract class TaxComputation {
public abstract double computeTax(PurchasedItems items,
ReceiptDate date);
public abstract boolean taxHoliday();
}
5
StoreItem Class
public class StoreItem {
private String itemCode; // e.g., 3010
private String itemDescription; // e.g., Dell Laptop
private String itemPrice;
public StoreItem(String code, String descript, String price)
{ ... }
// appropriate getters, setters and toString method
}
PurchasedItems Class
public class PurchasedItems {
private ArrayList<StoreItem> items;
public PurchasedItems() {
items = new ArrayList();
}
public void addItem(StoreItem item) { ... }
public double getTotalCost() { ... }
public boolean containsItem(String itemCode) { ... }
}
BasicReceipt Class
public class BasicReceipt implements Receipt {
private String storeInfo;
private String stateAbbrev;
// store number, store address, phone
number // AL, DE, GA, MD, NJ, or MO
private PurchasedItems items;
private Date date;
private TaxComputation tc;
public BasicReceipt(PurchasedItems items) {
this.items = items;
}
public void setTaxComputation(TaxComputation tc) { this.tc =
tc; }
public void setDate(String date) { this.date = date; }
public void prtReceipt() {
// to implement
}
}
6
AddOn Classes
Each of these classes is implemented to provide the information
for a particular secondary header, rebate
or coupon. The following are examples only of what these
classes may be.
public class HolidayGreeting implements AddOn,
SecondaryHeading {
public boolean applies(PurchasedItems items) {
return true; // SecondaryHeading decorators always applied
}
public String getLines() {
return “* Happy Holidays from Best Buy *”;
}
}
public class Rebate1406 implements AddOn, Rebate {
public boolean applies(PurchasedItems items) {
return items.containsItem(“1406”);
{
public String getLines() {
return “Mail-in Rebate for Item #1406n” + “Name:n” +
“Address:nn” +
“Mail to: Best Buy Rebates, P.O. Box 1400, Orlando, FL”;
}
}
public class Coupon100Get10Percent implements AddOn,
Coupon { // similar to rebate class }
Decorator Classes
There are two decorator class types - one for displaying text at
the top of a receipt (PreDecorator), and
another for displaying information at the bottom of a receipt
(PostDecorator). Each is constructed to
contain an AddOn object, which provides the added information
to be displayed on the receipt.
public class PreDecorator extends Decorator {
private AddOn a;
public PreDecorator(AddOn a, Receipt r) {
super(r);
this.a = a;
}
public void prtReceipt() {
System.out.println(a.getLines());
callTrailer();
}
}
public class PostDecorator extends Decorator
// similar, except that prtReceipt print the add on information
// after the other parts of the receipt are printed
7
Tax Computation Classes
public class MDTaxComputation extends TaxComputation {
public double computeTax(PurchasedItems items, ReceiptDate
date) {
// calls method taxHoliday as part of this computation
}
public boolean taxHoliday(ReceiptDate date);
// returns true if date of receipt within the state’s tax free
holiday,
// else returns false. Supporting method of method computeTax.
}
Tax computation objects for other states are similar
Factory Class
public class ReceiptFactory {
final String best_buy_name = “BEST BUY”;
String store_num;
String street_addr;
String phone;
String state_code;
private TaxComputation[] taxComputationsObjs; // tax
computation objects (one for each state)
private AddOn[] addOns; // secondary header, rebate and
coupon add-ons
public ReceiptFactory() { // constructor
// 1. Populates array of StateComputation objects and array of
AddOn objects (as if downloaded
from the BestBuy server).
// 2. Reads config file to assign store_num, street_addr, phone,
and state_code
// 3. Stores appropriate StateComputation object to be used on
all receipts.
}
public getReceipt(PurchasedItems items) {
// 1. Sets the current date of the BasicReceipt.
// 2. Attaches the StateComputation object to the BasicReceipt
(by call to the setComputation
method of BasicReceipt).
// 3. Traverses over all AddOn objects, calling the applies
method of each. If an AddOn object
applies, then determines if the AddOn is of type
SecondaryHeader, Rebate, or Coupon.
If of type SecondaryHeader, then creates a PreDecorator for the
AddOn. If of type Rebate or
Coupon, then creates a PostDecorator, and links in the decorator
object.
// 5. Assigns the state computation object for the state store
residing in.
// 6. Returns decorated BasicReceipt object as type Receipt.
}
}
8
CLIENT CODE
public static void main(String[] args)
{
// 1. Creates a PurchasedItems object.
// 2. Constructs ReceiptFactory object.
// 3. Prompts user for items to purchase, storing each in
PurchasedItems.
// 4. Calls the getReceipt method of the factory to obtain
constructed receipt.
// 5. Prints receipt by call to method prtReceipt() of the returned
receipt object.
// create Receipt factory
ReceiptFactory factory = new ReceiptFactory();
// get receipt date
// (get the current date by call to Java API)
while (!quit)
{
// create new PurchasedItems object
while (more purchased items)
{
// display all available products to user
(to be implemented)
// read selected item
(to be implemented)
// add to PurchasedItems
(to be completed)
}
Receipt receipt = factory.getReceipt(items, date);
receipt.prtReceipt();
// prompt if want to start a new receipt
(to be implemented)
}
}
PROGRAM TO CREATE
Create a program that will create of and display Best Buy
receipts. The program should provide a main
menu as in the following,
1 – Start New Receipt
2 – Add Items
3 – Display Receipt
4 – Quit
9
Vary the information in the configuration file and the AddOn
objects stored in the ReceiptFactory to check
that the factory builds the correct receipts for various situations
(e.g., in which only a BasicReceipt is
created; in which a Greeting AddOn exists; and in which
various combinations of Coupon and Rebate
AddOns exist).
WHAT TO TURN IN: Each of the source files, submitted as
one zipped file.

More Related Content

Similar to 1 – Implementing the Decorator Design Pattern (with St.docx

Check printing in_r12
Check printing in_r12Check printing in_r12
Check printing in_r12Rajesh Khatri
 
FDMEE script examples
FDMEE script examplesFDMEE script examples
FDMEE script examplesAmit Soni
 
FDMEE script examples
FDMEE script examplesFDMEE script examples
FDMEE script examplesAmit Sharma
 
Data warehousing unit 3.2
Data warehousing unit 3.2Data warehousing unit 3.2
Data warehousing unit 3.2WE-IT TUTORIALS
 
Tally.Erp 9 Job Costing Ver 1.0
Tally.Erp 9 Job Costing Ver 1.0Tally.Erp 9 Job Costing Ver 1.0
Tally.Erp 9 Job Costing Ver 1.0ravi78
 
Sales Process And Mrp
Sales Process And MrpSales Process And Mrp
Sales Process And MrpKiril Iliev
 
Porfolio of Setfocus work
Porfolio of Setfocus workPorfolio of Setfocus work
Porfolio of Setfocus workKevinPSF
 
Session4 J2ME Mobile Information Device Profile(MIDP) Events
Session4 J2ME Mobile Information Device Profile(MIDP) EventsSession4 J2ME Mobile Information Device Profile(MIDP) Events
Session4 J2ME Mobile Information Device Profile(MIDP) Eventsmuthusvm
 
Market Basket Analysis in SAS
Market Basket Analysis in SASMarket Basket Analysis in SAS
Market Basket Analysis in SASAndrew Kramer
 
exploring_a03_grader_h3.accdb (solution)
exploring_a03_grader_h3.accdb (solution)exploring_a03_grader_h3.accdb (solution)
exploring_a03_grader_h3.accdb (solution)JackCandtona
 
Sap mm release Strategy
Sap mm release StrategySap mm release Strategy
Sap mm release StrategyArnab Pal
 
.NET Code Examples
.NET Code Examples.NET Code Examples
.NET Code ExamplesGaryB47
 

Similar to 1 – Implementing the Decorator Design Pattern (with St.docx (20)

Check printing in_r12
Check printing in_r12Check printing in_r12
Check printing in_r12
 
FDMEE script examples
FDMEE script examplesFDMEE script examples
FDMEE script examples
 
FDMEE script examples
FDMEE script examplesFDMEE script examples
FDMEE script examples
 
Data warehousing unit 3.2
Data warehousing unit 3.2Data warehousing unit 3.2
Data warehousing unit 3.2
 
Tally.Erp 9 Job Costing Ver 1.0
Tally.Erp 9 Job Costing Ver 1.0Tally.Erp 9 Job Costing Ver 1.0
Tally.Erp 9 Job Costing Ver 1.0
 
Vending-machine.pdf
Vending-machine.pdfVending-machine.pdf
Vending-machine.pdf
 
SAP SD Training in Chennai
SAP SD Training in Chennai SAP SD Training in Chennai
SAP SD Training in Chennai
 
Data Warehousing
Data WarehousingData Warehousing
Data Warehousing
 
FactsVSM - Vansales Module
FactsVSM - Vansales ModuleFactsVSM - Vansales Module
FactsVSM - Vansales Module
 
Planning & Route Sheet.ppt
Planning & Route Sheet.pptPlanning & Route Sheet.ppt
Planning & Route Sheet.ppt
 
SAP MM Standard Business Processes
SAP MM Standard Business ProcessesSAP MM Standard Business Processes
SAP MM Standard Business Processes
 
171846965 projects
171846965 projects171846965 projects
171846965 projects
 
Sales Process And Mrp
Sales Process And MrpSales Process And Mrp
Sales Process And Mrp
 
Porfolio of Setfocus work
Porfolio of Setfocus workPorfolio of Setfocus work
Porfolio of Setfocus work
 
Session4 J2ME Mobile Information Device Profile(MIDP) Events
Session4 J2ME Mobile Information Device Profile(MIDP) EventsSession4 J2ME Mobile Information Device Profile(MIDP) Events
Session4 J2ME Mobile Information Device Profile(MIDP) Events
 
Market Basket Analysis in SAS
Market Basket Analysis in SASMarket Basket Analysis in SAS
Market Basket Analysis in SAS
 
exploring_a03_grader_h3.accdb (solution)
exploring_a03_grader_h3.accdb (solution)exploring_a03_grader_h3.accdb (solution)
exploring_a03_grader_h3.accdb (solution)
 
Sap mm release Strategy
Sap mm release StrategySap mm release Strategy
Sap mm release Strategy
 
.NET Code Examples
.NET Code Examples.NET Code Examples
.NET Code Examples
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 

More from honey725342

NRS-493 Individual Success PlanREQUIRED PRACTICE HOURS 100 Direct.docx
NRS-493 Individual Success PlanREQUIRED PRACTICE HOURS 100 Direct.docxNRS-493 Individual Success PlanREQUIRED PRACTICE HOURS 100 Direct.docx
NRS-493 Individual Success PlanREQUIRED PRACTICE HOURS 100 Direct.docxhoney725342
 
Now the Earth has had wide variations in atmospheric CO2-level throu.docx
Now the Earth has had wide variations in atmospheric CO2-level throu.docxNow the Earth has had wide variations in atmospheric CO2-level throu.docx
Now the Earth has had wide variations in atmospheric CO2-level throu.docxhoney725342
 
NR224 Fundamentals SkillsTopic Safety Goals BOOK P.docx
NR224 Fundamentals SkillsTopic Safety Goals BOOK P.docxNR224 Fundamentals SkillsTopic Safety Goals BOOK P.docx
NR224 Fundamentals SkillsTopic Safety Goals BOOK P.docxhoney725342
 
Nurse Education Today 87 (2020) 104348Contents lists avail.docx
Nurse Education Today 87 (2020) 104348Contents lists avail.docxNurse Education Today 87 (2020) 104348Contents lists avail.docx
Nurse Education Today 87 (2020) 104348Contents lists avail.docxhoney725342
 
Now that you’ve seen all of the elements contributing to the Devil’s.docx
Now that you’ve seen all of the elements contributing to the Devil’s.docxNow that you’ve seen all of the elements contributing to the Devil’s.docx
Now that you’ve seen all of the elements contributing to the Devil’s.docxhoney725342
 
NR360 We Can But Dare We.docx Revised 5 ‐ 9 .docx
NR360   We   Can   But   Dare   We.docx   Revised   5 ‐ 9 .docxNR360   We   Can   But   Dare   We.docx   Revised   5 ‐ 9 .docx
NR360 We Can But Dare We.docx Revised 5 ‐ 9 .docxhoney725342
 
Nurse Practitioner Diagnosis- Chest Pain.SOAPS-Subjective.docx
Nurse Practitioner Diagnosis- Chest Pain.SOAPS-Subjective.docxNurse Practitioner Diagnosis- Chest Pain.SOAPS-Subjective.docx
Nurse Practitioner Diagnosis- Chest Pain.SOAPS-Subjective.docxhoney725342
 
NURS 6002 Foundations of Graduate StudyAcademic and P.docx
NURS 6002 Foundations of Graduate StudyAcademic and P.docxNURS 6002 Foundations of Graduate StudyAcademic and P.docx
NURS 6002 Foundations of Graduate StudyAcademic and P.docxhoney725342
 
Nurse workforce shortage are predicted to get worse as baby boomers .docx
Nurse workforce shortage are predicted to get worse as baby boomers .docxNurse workforce shortage are predicted to get worse as baby boomers .docx
Nurse workforce shortage are predicted to get worse as baby boomers .docxhoney725342
 
Now, for the exam itself. Below are 4 questions. You need to answer .docx
Now, for the exam itself. Below are 4 questions. You need to answer .docxNow, for the exam itself. Below are 4 questions. You need to answer .docx
Now, for the exam itself. Below are 4 questions. You need to answer .docxhoney725342
 
Nur-501-AP4- Philosophical and Theoretical Evidence-Based research.docx
Nur-501-AP4- Philosophical and Theoretical Evidence-Based research.docxNur-501-AP4- Philosophical and Theoretical Evidence-Based research.docx
Nur-501-AP4- Philosophical and Theoretical Evidence-Based research.docxhoney725342
 
NU32CH19-Foltz ARI 9 July 2012 1945Population-Level Inter.docx
NU32CH19-Foltz ARI 9 July 2012 1945Population-Level Inter.docxNU32CH19-Foltz ARI 9 July 2012 1945Population-Level Inter.docx
NU32CH19-Foltz ARI 9 July 2012 1945Population-Level Inter.docxhoney725342
 
Nurse Working in the CommunityDescribe the community nurses.docx
Nurse Working in the CommunityDescribe the community nurses.docxNurse Working in the CommunityDescribe the community nurses.docx
Nurse Working in the CommunityDescribe the community nurses.docxhoney725342
 
nursing diagnosis1. Decreased Cardiac Output  related to Alter.docx
nursing diagnosis1. Decreased Cardiac Output  related to Alter.docxnursing diagnosis1. Decreased Cardiac Output  related to Alter.docx
nursing diagnosis1. Decreased Cardiac Output  related to Alter.docxhoney725342
 
Nursing Documentation Is it valuable Discuss the value of nursin.docx
Nursing Documentation Is it valuable Discuss the value of nursin.docxNursing Documentation Is it valuable Discuss the value of nursin.docx
Nursing Documentation Is it valuable Discuss the value of nursin.docxhoney725342
 
NR631 Concluding Graduate Experience - Scope Project Managemen.docx
NR631 Concluding Graduate Experience - Scope  Project Managemen.docxNR631 Concluding Graduate Experience - Scope  Project Managemen.docx
NR631 Concluding Graduate Experience - Scope Project Managemen.docxhoney725342
 
Number 11. Describe at least five populations who are vulner.docx
Number 11. Describe at least five populations who are vulner.docxNumber 11. Describe at least five populations who are vulner.docx
Number 11. Describe at least five populations who are vulner.docxhoney725342
 
ntertainment, the media, and sometimes public leaders can perpetuate.docx
ntertainment, the media, and sometimes public leaders can perpetuate.docxntertainment, the media, and sometimes public leaders can perpetuate.docx
ntertainment, the media, and sometimes public leaders can perpetuate.docxhoney725342
 
Now that you have  completed Lesson 23 & 24 and have thought a.docx
Now that you have  completed Lesson 23 & 24 and have thought a.docxNow that you have  completed Lesson 23 & 24 and have thought a.docx
Now that you have  completed Lesson 23 & 24 and have thought a.docxhoney725342
 
nothing wrong with the paper, my professor just wants it to be in an.docx
nothing wrong with the paper, my professor just wants it to be in an.docxnothing wrong with the paper, my professor just wants it to be in an.docx
nothing wrong with the paper, my professor just wants it to be in an.docxhoney725342
 

More from honey725342 (20)

NRS-493 Individual Success PlanREQUIRED PRACTICE HOURS 100 Direct.docx
NRS-493 Individual Success PlanREQUIRED PRACTICE HOURS 100 Direct.docxNRS-493 Individual Success PlanREQUIRED PRACTICE HOURS 100 Direct.docx
NRS-493 Individual Success PlanREQUIRED PRACTICE HOURS 100 Direct.docx
 
Now the Earth has had wide variations in atmospheric CO2-level throu.docx
Now the Earth has had wide variations in atmospheric CO2-level throu.docxNow the Earth has had wide variations in atmospheric CO2-level throu.docx
Now the Earth has had wide variations in atmospheric CO2-level throu.docx
 
NR224 Fundamentals SkillsTopic Safety Goals BOOK P.docx
NR224 Fundamentals SkillsTopic Safety Goals BOOK P.docxNR224 Fundamentals SkillsTopic Safety Goals BOOK P.docx
NR224 Fundamentals SkillsTopic Safety Goals BOOK P.docx
 
Nurse Education Today 87 (2020) 104348Contents lists avail.docx
Nurse Education Today 87 (2020) 104348Contents lists avail.docxNurse Education Today 87 (2020) 104348Contents lists avail.docx
Nurse Education Today 87 (2020) 104348Contents lists avail.docx
 
Now that you’ve seen all of the elements contributing to the Devil’s.docx
Now that you’ve seen all of the elements contributing to the Devil’s.docxNow that you’ve seen all of the elements contributing to the Devil’s.docx
Now that you’ve seen all of the elements contributing to the Devil’s.docx
 
NR360 We Can But Dare We.docx Revised 5 ‐ 9 .docx
NR360   We   Can   But   Dare   We.docx   Revised   5 ‐ 9 .docxNR360   We   Can   But   Dare   We.docx   Revised   5 ‐ 9 .docx
NR360 We Can But Dare We.docx Revised 5 ‐ 9 .docx
 
Nurse Practitioner Diagnosis- Chest Pain.SOAPS-Subjective.docx
Nurse Practitioner Diagnosis- Chest Pain.SOAPS-Subjective.docxNurse Practitioner Diagnosis- Chest Pain.SOAPS-Subjective.docx
Nurse Practitioner Diagnosis- Chest Pain.SOAPS-Subjective.docx
 
NURS 6002 Foundations of Graduate StudyAcademic and P.docx
NURS 6002 Foundations of Graduate StudyAcademic and P.docxNURS 6002 Foundations of Graduate StudyAcademic and P.docx
NURS 6002 Foundations of Graduate StudyAcademic and P.docx
 
Nurse workforce shortage are predicted to get worse as baby boomers .docx
Nurse workforce shortage are predicted to get worse as baby boomers .docxNurse workforce shortage are predicted to get worse as baby boomers .docx
Nurse workforce shortage are predicted to get worse as baby boomers .docx
 
Now, for the exam itself. Below are 4 questions. You need to answer .docx
Now, for the exam itself. Below are 4 questions. You need to answer .docxNow, for the exam itself. Below are 4 questions. You need to answer .docx
Now, for the exam itself. Below are 4 questions. You need to answer .docx
 
Nur-501-AP4- Philosophical and Theoretical Evidence-Based research.docx
Nur-501-AP4- Philosophical and Theoretical Evidence-Based research.docxNur-501-AP4- Philosophical and Theoretical Evidence-Based research.docx
Nur-501-AP4- Philosophical and Theoretical Evidence-Based research.docx
 
NU32CH19-Foltz ARI 9 July 2012 1945Population-Level Inter.docx
NU32CH19-Foltz ARI 9 July 2012 1945Population-Level Inter.docxNU32CH19-Foltz ARI 9 July 2012 1945Population-Level Inter.docx
NU32CH19-Foltz ARI 9 July 2012 1945Population-Level Inter.docx
 
Nurse Working in the CommunityDescribe the community nurses.docx
Nurse Working in the CommunityDescribe the community nurses.docxNurse Working in the CommunityDescribe the community nurses.docx
Nurse Working in the CommunityDescribe the community nurses.docx
 
nursing diagnosis1. Decreased Cardiac Output  related to Alter.docx
nursing diagnosis1. Decreased Cardiac Output  related to Alter.docxnursing diagnosis1. Decreased Cardiac Output  related to Alter.docx
nursing diagnosis1. Decreased Cardiac Output  related to Alter.docx
 
Nursing Documentation Is it valuable Discuss the value of nursin.docx
Nursing Documentation Is it valuable Discuss the value of nursin.docxNursing Documentation Is it valuable Discuss the value of nursin.docx
Nursing Documentation Is it valuable Discuss the value of nursin.docx
 
NR631 Concluding Graduate Experience - Scope Project Managemen.docx
NR631 Concluding Graduate Experience - Scope  Project Managemen.docxNR631 Concluding Graduate Experience - Scope  Project Managemen.docx
NR631 Concluding Graduate Experience - Scope Project Managemen.docx
 
Number 11. Describe at least five populations who are vulner.docx
Number 11. Describe at least five populations who are vulner.docxNumber 11. Describe at least five populations who are vulner.docx
Number 11. Describe at least five populations who are vulner.docx
 
ntertainment, the media, and sometimes public leaders can perpetuate.docx
ntertainment, the media, and sometimes public leaders can perpetuate.docxntertainment, the media, and sometimes public leaders can perpetuate.docx
ntertainment, the media, and sometimes public leaders can perpetuate.docx
 
Now that you have  completed Lesson 23 & 24 and have thought a.docx
Now that you have  completed Lesson 23 & 24 and have thought a.docxNow that you have  completed Lesson 23 & 24 and have thought a.docx
Now that you have  completed Lesson 23 & 24 and have thought a.docx
 
nothing wrong with the paper, my professor just wants it to be in an.docx
nothing wrong with the paper, my professor just wants it to be in an.docxnothing wrong with the paper, my professor just wants it to be in an.docx
nothing wrong with the paper, my professor just wants it to be in an.docx
 

Recently uploaded

COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Ernest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsErnest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsPallavi Parmar
 
Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfElizabeth Walsh
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaEADTU
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfNirmal Dwivedi
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Celine George
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdf
Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdfDiuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdf
Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdfKartik Tiwari
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111GangaMaiya1
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxakanksha16arora
 

Recently uploaded (20)

COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Ernest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsErnest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell Tolls
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdf
Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdfDiuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdf
Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdf
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 

1 – Implementing the Decorator Design Pattern (with St.docx

  • 1. 1 – Implementing the Decorator Design Pattern (with Strategy Pattern and Factory Class) ) PROBLEM You are to design and implement code based on the Decorator pattern for generating an appropriate receipt for a customer buying items at a particular Best Buy store. The general format of a receipt is as follows: Basic Receipt Store Header (store street address, state abbreviation, phone number, store number) Date of Sale Itemized Purchases Total Sale (without sales tax) Amount Due (with added sales tax) Dynamically-Added Items Tax Computation object (based on state residing in) Optional Secondary Headers (“Greetings”) to be printed at the very top of the receipt, e.g., - “Happy Holidays from Best Buy” - “Summer Sales are Hot at Best Buy”
  • 2. Relevant Rebate Forms (to be printed at the end of the receipt) Promotional Coupons (to be printed at the end of the receipt) e.g., “10% off next purchase of $100 or more” coupon APPROACH We will assume that the code is written as part of the software used by all Best Buy stores around the country. Therefore, the information in the Store Header will vary depending on the particular store's location. In addition, the amount of sales tax (if any) is determined by the state that the store resides in, and included in a receipt by use of the Strategy pattern. The added items to be displayed on each receipt (i.e.,. greeting secondary header, rebate form or coupon) will be handled by use of the Decorator pattern. Finally, the receipt will be constructed by use of the Factory class pattern. Basic Receipt The information for the basic receipt should be stored in a BasicReceipt object (see below). The instance variables of a BasicReceipt should contain the date of sale, a PurchasedItems object, the total sale (without tax) and amount due (with added tax), each of type float. In addition, following the Strategy design pattern, there should be an instance variable of (interface) type TaxComputation that can be assigned the appropriate tax computation object (e.g., NJTaxComputation) for the state that the store resides in.
  • 3. 2 Determining Sales Tax We will implement tax computation classes so that receipts can be generated for one of five possible states: Alabama (4%), Delaware (no sales tax), Georgia (4%), Maryland (6%) and Missouri (4.225%). Note that a number of states have a “sales tax holidays” in which certain items are not taxed (e.g., clothers, computers) in preparation of the new school year. These holidays normally last for 2-4 days over at weekend at the end of summer (e.g., the first weekend in August). Use the information provided in Wikipedia about states with a tax holiday (here) to implement a state computation object that would properly compute the sales tax of a given state, for a certain set of purchased items, for the current or any future year. (Note that we will assume that anything purchased in Best Buy is a computer-related item.) Adding Additional Receipt Items There are a number of different “add on” items that may need to be printed with the basic receipt. During particular times of the year, a receipt header may begin with a special greeting (e.g., “Happy Holidays from Best Buy”), called a secondary header, to be added to the top of a receipt. In addition, rebate forms may be printed at the end of a receipt if a purchased item has a mail-in rebate. Finally, coupons may be printed (also at the end of a receipt) if the total purchase exceeds a certain dollar amount (e.g., if spend over $100, get a 10% off coupon for the next
  • 4. visit). Objects of interface type AddOn are used to store the added printout for a receipt. The interface has two methods - applies (which is passed a PurchasedItems object containing all of the items for the current receipt), and getLines (which returns the added lines of text to be printed as a single String with embedded newline characters). For AddOn objects of type SecondaryHeader, applies always returns true. This is because if a SecondaryHeader exists, it is always added to the (top) of the receipt. Since rebates only apply to a specific item, method applies returns true if and only if the particular item is found in PurchasedItems. A similar approach is taken for adding coupons to the end of a receipt, except that coupons apply if and only if the customer has spent over a certain amount. We assume that each Best Buy store downloads the current set of decorator objects each morning. Configuration File A configuration file will be read by the program at start up, to configure the system for the particular store location, containing the following information: store street address, state abbreviation, phone number, and store number. Factory Class You must utilize a factory class to properly construct Best Buy receipts based on the information read from the configuration file, and the particular items purchased.
  • 5. A UML class diagram for the design of this program is given below. http://en.wikipedia.org/wiki/Sales_tax_holiday 3 4 INTERFACES AND CLASSES TO UTILIZE Following are the interface and classes to be used in the design of the program. Interfaces public interface Receipt { // type of all receipt components (i.e., BasicReceipt and receipt decorators) public void prtReceipt(); } public interface AddOn { // the type of added info to a BasicReceipt (e.g., greetings, rebates, coupons) public boolean applies(PurchasedItems items); public String getLines(); } public interface SecondaryHeading { // marker interface, i.e., nothing to implement }
  • 6. public interface Rebate { // marker interface, i.e., nothing to implement } public interface Coupon { // marker interface, i.e., nothing to implement } Abstract Classes public abstract class Decorator implements Receipt { private Receipt trailer; public Decorator(Receipt r) { trailer = r; } protected void callTrailer() { trailer.prtReceipt(); } public abstract void prtReceipt(); } public abstract class TaxComputation { public abstract double computeTax(PurchasedItems items, ReceiptDate date); public abstract boolean taxHoliday(); }
  • 7. 5 StoreItem Class public class StoreItem { private String itemCode; // e.g., 3010 private String itemDescription; // e.g., Dell Laptop private String itemPrice; public StoreItem(String code, String descript, String price) { ... } // appropriate getters, setters and toString method } PurchasedItems Class public class PurchasedItems { private ArrayList<StoreItem> items; public PurchasedItems() { items = new ArrayList(); } public void addItem(StoreItem item) { ... } public double getTotalCost() { ... } public boolean containsItem(String itemCode) { ... } } BasicReceipt Class public class BasicReceipt implements Receipt { private String storeInfo;
  • 8. private String stateAbbrev; // store number, store address, phone number // AL, DE, GA, MD, NJ, or MO private PurchasedItems items; private Date date; private TaxComputation tc; public BasicReceipt(PurchasedItems items) { this.items = items; } public void setTaxComputation(TaxComputation tc) { this.tc = tc; } public void setDate(String date) { this.date = date; } public void prtReceipt() { // to implement } } 6 AddOn Classes Each of these classes is implemented to provide the information for a particular secondary header, rebate or coupon. The following are examples only of what these classes may be.
  • 9. public class HolidayGreeting implements AddOn, SecondaryHeading { public boolean applies(PurchasedItems items) { return true; // SecondaryHeading decorators always applied } public String getLines() { return “* Happy Holidays from Best Buy *”; } } public class Rebate1406 implements AddOn, Rebate { public boolean applies(PurchasedItems items) { return items.containsItem(“1406”); { public String getLines() { return “Mail-in Rebate for Item #1406n” + “Name:n” + “Address:nn” + “Mail to: Best Buy Rebates, P.O. Box 1400, Orlando, FL”; } } public class Coupon100Get10Percent implements AddOn, Coupon { // similar to rebate class } Decorator Classes There are two decorator class types - one for displaying text at the top of a receipt (PreDecorator), and
  • 10. another for displaying information at the bottom of a receipt (PostDecorator). Each is constructed to contain an AddOn object, which provides the added information to be displayed on the receipt. public class PreDecorator extends Decorator { private AddOn a; public PreDecorator(AddOn a, Receipt r) { super(r); this.a = a; } public void prtReceipt() { System.out.println(a.getLines()); callTrailer(); } } public class PostDecorator extends Decorator // similar, except that prtReceipt print the add on information // after the other parts of the receipt are printed 7 Tax Computation Classes public class MDTaxComputation extends TaxComputation { public double computeTax(PurchasedItems items, ReceiptDate date) { // calls method taxHoliday as part of this computation
  • 11. } public boolean taxHoliday(ReceiptDate date); // returns true if date of receipt within the state’s tax free holiday, // else returns false. Supporting method of method computeTax. } Tax computation objects for other states are similar Factory Class public class ReceiptFactory { final String best_buy_name = “BEST BUY”; String store_num; String street_addr; String phone; String state_code; private TaxComputation[] taxComputationsObjs; // tax computation objects (one for each state) private AddOn[] addOns; // secondary header, rebate and coupon add-ons public ReceiptFactory() { // constructor // 1. Populates array of StateComputation objects and array of AddOn objects (as if downloaded from the BestBuy server). // 2. Reads config file to assign store_num, street_addr, phone, and state_code
  • 12. // 3. Stores appropriate StateComputation object to be used on all receipts. } public getReceipt(PurchasedItems items) { // 1. Sets the current date of the BasicReceipt. // 2. Attaches the StateComputation object to the BasicReceipt (by call to the setComputation method of BasicReceipt). // 3. Traverses over all AddOn objects, calling the applies method of each. If an AddOn object applies, then determines if the AddOn is of type SecondaryHeader, Rebate, or Coupon. If of type SecondaryHeader, then creates a PreDecorator for the AddOn. If of type Rebate or Coupon, then creates a PostDecorator, and links in the decorator object. // 5. Assigns the state computation object for the state store residing in. // 6. Returns decorated BasicReceipt object as type Receipt. } } 8 CLIENT CODE
  • 13. public static void main(String[] args) { // 1. Creates a PurchasedItems object. // 2. Constructs ReceiptFactory object. // 3. Prompts user for items to purchase, storing each in PurchasedItems. // 4. Calls the getReceipt method of the factory to obtain constructed receipt. // 5. Prints receipt by call to method prtReceipt() of the returned receipt object. // create Receipt factory ReceiptFactory factory = new ReceiptFactory(); // get receipt date // (get the current date by call to Java API) while (!quit) { // create new PurchasedItems object while (more purchased items) { // display all available products to user (to be implemented) // read selected item (to be implemented) // add to PurchasedItems (to be completed) }
  • 14. Receipt receipt = factory.getReceipt(items, date); receipt.prtReceipt(); // prompt if want to start a new receipt (to be implemented) } } PROGRAM TO CREATE Create a program that will create of and display Best Buy receipts. The program should provide a main menu as in the following, 1 – Start New Receipt 2 – Add Items 3 – Display Receipt 4 – Quit 9 Vary the information in the configuration file and the AddOn objects stored in the ReceiptFactory to check that the factory builds the correct receipts for various situations (e.g., in which only a BasicReceipt is created; in which a Greeting AddOn exists; and in which various combinations of Coupon and Rebate AddOns exist).
  • 15. WHAT TO TURN IN: Each of the source files, submitted as one zipped file.