This document discusses several design patterns: Factory, Flyweight, Singleton, Observer, Proxy, Decorator. It provides definitions and examples of when to use each pattern. The Factory pattern creates objects without specifying the exact class. Flyweight reduces memory usage by sharing instances. Singleton ensures only one instance exists. Observer notifies dependent objects of state changes. Proxy controls access to another object. Decorator adds new behaviors to an object dynamically.
Projects In Laravel : Learn Laravel Building 10 ProjectsSam Dias
Projects In Laravel : Learn Laravel Building 10 Projects
Learn Laravel 5, top PHP framework, including how to install Laravel 5 framework & fundamentals in this Laravel 5 tutorial. This is why you need something to help you learn a technology quickly and easily! Our course does exactly that!
https://www.eduonix.com/courses/Web-Development/projects-in-laravel-learn-laravel-building-10-projects
Projects In Laravel : Learn Laravel Building 10 ProjectsSam Dias
Projects In Laravel : Learn Laravel Building 10 Projects
Learn Laravel 5, top PHP framework, including how to install Laravel 5 framework & fundamentals in this Laravel 5 tutorial. This is why you need something to help you learn a technology quickly and easily! Our course does exactly that!
https://www.eduonix.com/courses/Web-Development/projects-in-laravel-learn-laravel-building-10-projects
Presented at JavaOne 2013, Tuesday September 24.
"Data Modeling Patterns" co-created with Ian Robinson.
"Pitfalls and Anti-Patterns" created by Ian Robinson.
Python/Flask is one of the most popular choices for Developers when it comes to creating a Web Application. Learn how you can get started with making your Web Application using Python and Flask in this presentation.
Here are Github links for Sample Application that we Demonstrated -
https://github.com/mohanrohit/reading-list-api
https://github.com/mohanrohit/reading-list-web
(Powered by www.DeepDiveEducation.com)
Architecting Large Enterprise Java ProjectsMarkus Eisele
In the past I've been building component oriented applications with what I had at hand. Mostly driven by the features available in the Java EE standard to be "portable" and easy to use. Looking back this has been a perfect fit for many customers and applications. With an increasing demand for highly integrated applications which use already available services and processes from all over the place (departmental, central or even cloud services) this approach starts to feel more and more outdated. And this feel does not come from a technology perspective but from all the requirements around it. Having this in mind this post is the starting point of a series of how-to's and short tutorials which aim to showcase some more diverse ways of building (Java EE) applications that fit better into today's requirements and landscapes.
Presented at JavaOne 2013, Tuesday September 24.
"Data Modeling Patterns" co-created with Ian Robinson.
"Pitfalls and Anti-Patterns" created by Ian Robinson.
Python/Flask is one of the most popular choices for Developers when it comes to creating a Web Application. Learn how you can get started with making your Web Application using Python and Flask in this presentation.
Here are Github links for Sample Application that we Demonstrated -
https://github.com/mohanrohit/reading-list-api
https://github.com/mohanrohit/reading-list-web
(Powered by www.DeepDiveEducation.com)
Architecting Large Enterprise Java ProjectsMarkus Eisele
In the past I've been building component oriented applications with what I had at hand. Mostly driven by the features available in the Java EE standard to be "portable" and easy to use. Looking back this has been a perfect fit for many customers and applications. With an increasing demand for highly integrated applications which use already available services and processes from all over the place (departmental, central or even cloud services) this approach starts to feel more and more outdated. And this feel does not come from a technology perspective but from all the requirements around it. Having this in mind this post is the starting point of a series of how-to's and short tutorials which aim to showcase some more diverse ways of building (Java EE) applications that fit better into today's requirements and landscapes.
When it comes to any kind of marketing you need to look at what kind of results you are going to get. With your website, you also need to use goals and objectives to make sure your investment is working. This presentation talks about Setting up and Using Sales Goals tied with your website & inbound marketing.
10 Important Tips For Increasing Traffic On Your WebsiteEminenture
Everyone wants to get more traffic to their website but it is not so easy. It requires good understanding of search engine algorithms. Advertising through social media, socializing your content, visualizing your content for making it more effective, SEO, using long-tailed keywords, guest blogging and interlinking of web pages can drive a huge traffic to your website.
Website analysis and Competitor Analysis and Website WireframeSaloni Jain
I've done the Website analysis and Competitor Analysis and Website Wireframe for the website www.shoefetish.com All this data has been made using Google Adwords
When a software project is considered, what all phases it has to go through for its completion & closure. What are the specifications to be made is explained here. Online shopping Portal is our project and its in-scope & out-scope are also specified.
I was asked to do a sales presentation as part of an interview and this is the "wireframe" (can I call it so?) or template of the presentation for your reference.
You may choose to give credits to your references or sources at the end. I did it as I wanted to show the research I had done before meeting the interview panel.
Gephi Toolkit Developer Tutorial.
The Gephi Toolkit project package essential modules (Graph, Layout, Filters, IO...) in a standard Java library, which any Java project can use for getting things done. The toolkit is just a single JAR that anyone could reuse.
This tutorial introduce the project, show possibilities and code examples to get started.
Since these presentations were spare time hobby - I've decided to share them :)
Hopefully someone will find them useful.
This part continues 1. part with more design patterns like Command, State, NullObject.
GPars (Groovy Parallel Systems) is an open-source concurrency and parallelism library for Java and Groovy that gives you a number of high-level abstractions for writing concurrent and parallel code in Groovy (map/reduce, fork/join, asynchronous closures, actors, agents, dataflow concurrency and other concepts), which can make your Java and Groovy code concurrent and/or parallel with little effort.
MongoDB is the trusted document store we turn to when we have tough data store problems to solve. For this talk we are going to go a little bit off the path and explore what other roles we can fit MongoDB into. Others have discussed how to turn MongoDB’s capped collections into a publish/subscribe server. We stretch that a little further and turn MongoDB into a full fledged broker with both publish/subscribe and queue semantics, and a the ability to mix them. We will provide code and a running demo of the queue producers and consumers. Next we will turn to coordination services: We will explore the fundamental features and show how to implement them using MongoDB as the storage engine. Again we will show the code and demo the coordination of multiple applications.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
2. What Are Design Patterns?
A solution to a language
independent OO Problem.
If the solution is a
reoccurring over time, it
becomes a “Pattern”.
.net
Java
C++
C#
VB.net
3. Factory Pattern
Definition
The Factory pattern provides a way to use an instance as a object
factory. The factory can return an instance of one of several possible
classes (in a subclass hierarchy), depending on the data provided to
it.
Where to use
1) When a class can't anticipate which kind of class of object it must
create.
2) You want to localize the knowledge of which class gets created.
3) When you have classes that is derived from the same subclasses,
or they may in fact be unrelated classes that just share the same
interface. Either way, the methods in these class instances are the
same and can be used interchangeably.
4) When you want to insulate the client from the actual type that is
being instantiated.
5. Factory Patternpublic abstract class Product {
public void writeName(String name) {
System.out.println("My name is "+name);
}
}
public class ProductA extends Product { }
public class ProductB extends Product {
public void writeName(String name) {
StringBuilder tempName = new StringBuilder().append(name);
System.out.println("My reversed name is" + tempName.reverse());
}
}
public class ProductFactory {
public Product createProduct(String type) {
if(type.equals("B"))
return new ProductB();
else
return new ProductA();
}
}
ProductFactory pf = new ProductFactory();
Product prod;
prod = pf.createProduct("A");
prod.writeName("John Doe");
prod = pf.createProduct("B");
prod.writeName("John Doe");
Connection, Statement, ResultSet
6. Proxy Pattern
DefinitionDefinition
A Proxy is a structural pattern that provides a stand-in for
another object in order to control access to it.
Where to useWhere to use
1) When the creation of one object is relatively expensive it can be a
good idea to replace it with a proxy that can make sure that
instantiation of the expensive object is kept to a minimum.
2) Proxy pattern implementation allows for login and authority
checking before one reaches the actual object that's requested.
3) Can provide a local representation for an object in a remote
location.
8. Proxy Patterninterface IExploded {
public void pumpPetrol(String arg);
}
class ProxyExploded implements IExploded{
public void pumpPetrol(String arg){
System.out.println("Pumping. ");
}
}
public class Pattern_Proxy implements IExploded
{
StringBuffer strbuf = new StringBuffer();
public void pumpPetrol(String arg){
strbuf.append(arg);
System.out.println("Pumping. ");
if(strbuf.length() >70){
explosion2(); strbuf.delete(0, strbuf.length()); System.exit(0);
}else if(strbuf.length()>50){
explosion1();
}
}
public void explosion1(){ System.out.println("System is about to Explode"); }
public void explosion2(){
System.out.println("System has exploded... Kaboom!!.. rn”+
”To Much Petrol.."+strbuf.length()+" L");
}
}
public static void main(String arg[])
{
IExploded prox = new Pattern_Proxy();
for(int y=0; y<50; y++){
prox.pumpPetrol("Petrol.");
}
}
9. Singleton Pattern
Definition
The Singleton pattern provides the possibility to control the
number of instances (mostly one) that are allowed to be
made. We also receive a global point of access to it (them).
Where to use
When only one instance or a specific number of instances of
a class are allowed. Facade objects are often Singletons
because only one Facade object is required.
Benefits
•Controlled access to unique instance.
•Reduced name space.
•Allows refinement of operations and representations.
11. Singleton Pattern
public class MapLogger
{
private static MapLogger mapper=null;
// Prevent clients from using the constructor
private MapLogger() { /* Nothing Here :-) */ }
//Control the accessible (allowed) instances
public static MapLogger getMapLogger() {
if (mapper == null) {
mapper = new MapLogger();
}
return mapper;
}
public synchronized void put(String key, String val)
{
// Write to Map/Hashtable...
}
}
12. Flyweight Pattern
Definition
The Flyweight pattern provides a mechanism by which you can
avoid creating a large number of 'expensive' objects and instead
reuse existing instances to represent new ones.
Where to use
1) When there is a very large number of objects that may not fit in
memory.
2) When most of an objects state can be stored on disk or calculated
at Runtime.
3) When there are groups of objects that share state.
4) When the remaining state can be factored into a much smaller
number of objects with shared state.
Benefits
Reduce the number of objects created, decrease memory footprint
and increase performance.
14. Flyweight Patternclass Godzilla {
private int row;
public Godzilla( int theRow ) {
row = theRow;
System.out.println( "ctor: " + row );
}
void report( int theCol ) {
System.out.print( " " + row + theCol );
}
} class Factory {
private Godzilla[] pool;
public Factory( int maxRows ) {
pool = new Godzilla[maxRows];
}
public Godzilla getFlyweight( int theRow ) {
if (pool[theRow] == null)
pool[theRow] = new Godzilla( theRow );
return pool[theRow];
}
}
public class FlyweightDemo {
public static final int ROWS = 6, COLS = 10;
public static void main( String[] args ) {
Factory theFactory = new Factory( ROWS );
for (int i=0; i < ROWS; i++) {
for (int j=0; j < COLS; j++)
theFactory.getFlyweight( i ).report( j );
System.out.println();
} } }
15. Observer Pattern
Definition
Proxy pattern is a behavioral pattern. It defines a one-to-many
dependency between objects, so that when one object changes its
state, all its dependent objects are notified and updated.
Where to use
1) When state changes of a one object must be reflected in other
objects without depending on the state changing process of the object
(reduce the coupling between the objects).
17. Observer Pattern
public class WeatherStation extends Observable implements Runnable {
public void run() {
String report = this.getCurrentReport();
notifyObservers( report );
}
}
public class WeatherObserver implements Observer {
private String response;
public void update (Observable obj, Object arg) {
response = (String)arg;
}
}
18. Observer Pattern
public class WeatherClient {
public static void main(String args[]) {
// create a WheatherStation instance
final WeatherStation station = new WeatherStation();
// create an observer
final WeatherObserver weatherObserver = new WeatherObserver();
// subscribe the observer to the event source
station.addObserver( weatherObserver );
// starts the event thread
Thread thread = new Thread(station);
thread.start();
}
}
19. Decorator Pattern
Definition
Decorator pattern is a structural pattern. Intent of the pattern is to add
additional responsibilities dynamically to an object.
Where to use
1) When you want the responsibilities added to or removed from an
object at runtime.
2) When using inheritance results in a large number of subclasses.
21. Decorator Pattern
// The Coffee Interface defines the functionality of Coffee implemented by
decorator
public interface Coffee {
// returns the cost of the coffee
public double getCost();
// returns the ingredients of the coffee
public String getIngredients();
}
// implementation of a simple coffee without any extra ingredients
public class SimpleCoffee implements Coffee {
public double getCost() {
return 1;
}
public String getIngredients() {
return "Coffee";
}
}
22. Decorator Pattern
// abstract decorator class - note that it implements Coffee interface
abstract public class CoffeeDecorator implements Coffee {
protected final Coffee decoratedCoffee;
protected String ingredientSeparator = ", ";
public CoffeeDecorator(Coffee decoratedCoffee) {
this.decoratedCoffee = decoratedCoffee;
}
public double getCost() {
// implementing methods of the interface
return decoratedCoffee.getCost();
}
public String getIngredients() {
return decoratedCoffee.getIngredients();
}
}
23. Decorator Pattern
// Decorator Milk that mixes milk with coffee
// note it extends CoffeeDecorator
public class Milk extends CoffeeDecorator {
public Milk(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
// overriding methods defined in the abstract superclass
return super.getCost() + 0.5;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Milk";
}
}
24. Decorator Pattern
public class Whip extends CoffeeDecorator {
public Whip(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
return super.getCost() + 0.7;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Whip";
}
}
25. Decorator Pattern
public class CoffeMaker {
public static void main(String[] args) {
Coffee c = new SimpleCoffee();
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
c = new Milk(c);
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
}
}
26. Decorator Pattern
public class Whip extends CoffeeDecorator {
public Whip(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
return super.getCost() + 0.7;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Whip";
}
}