Sie sind auf Seite 1von 29

1.

Expert Pattern
Pattern Instance:

Class Diagram

Implementation:
ProductDescription.java
import java.util.Scanner;
public class ProductDescription {
public SaleCounter saleCounter;
private SaleCounter sc;
private float price ;
public float getPrice() {
Scanner sr = new Scanner(System.in);
System.out.println("Enter the price");
price = sr.nextFloat();
return price;
}
}

Sale.java
public class Sale {
private float total;
public float getTotal() {
ProductDescription pd = new ProductDescription();
SaleLineItem sli = new SaleLineItem();
total = pd.getPrice()*sli.getQuantity();
return total;
}
}
SaleLineItem.java
import java.util.Scanner;
public class SaleLineItem {
public SaleCounter saleCounter;
private SaleCounter sc;
private int quantity;
public int getQuantity() {
Scanner sr = new Scanner(System.in);
System.out.println("Enter the quantity");
quantity = sr.nextInt();
return quantity;
}
}
SaleCounter.java
public class SaleCounter {
public SaleLineItem saleLineItem;
private ProductDescription pd;
private Sale s;
private SaleLineItem sli;
public static void main(String[] args) {// TODO Auto-generated method
stub
float total;
Sale s = new Sale();
total = s.getTotal();
System.out.println("Total is"+total);
}
}
OUTPUT:
Enter the price
100
Enter the quantity
25
Total is2500.0

2.Controller Pattern
Pattern Instance

Class Diagram

Implementation:
Client.java
import java.util.Scanner;
public class Client {
public TheController theController;
public static SaleController getController() {
SaleController sc = new SaleController();
Sale s =new Sale();
View v = new View();
sc.setSale(s);
sc.setView(v);
return sc;
}
public static void main(String[] args) {// TODO Auto-generated method
stub
SaleController sc = getController();

Scanner sr = new Scanner(System.in);


System.out.println("Enter Quantity");
int quantity = sr.nextInt();
System.out.println("Enter price");
float price = sr.nextFloat();
sc.execute(quantity, price);
}
}
Sale.java
public class Sale {
public SaleController saleController;
public float getTotal(int quantity,float price) {// TODO Auto-generated
method stub
return quantity*price;
}
}
SaleController.java
public class SaleController {
public Client client;
public void execute(int quantity,float price) {// TODO Auto-generated
method stub
float result= sale.getTotal(quantity, price);
view.display(result);
}
}
View.java
public class View {
public void display(float total) {// TODO Auto-generated method stub
System.out.println("The total sale"+total);
}
}
OUTPUT
Enter Quantity
10
Enter price
25.2
The total sale252.0

3.Publisher-Subscriber Pattern
Pattern Instance

Class Diagram

Implementation:
Indicator.java:
import java.util.Observable;
import java.util.Observer;
public class Indicator implements Observer {
public void display() {
System.out.println("Indicator Data");
float y1=(this.temperature) - (100);
float y2=(100) - (this.temperature);
if(this.temperature > 100)
System.out.println("Temperature is Off By :"+y1);
else
System.out.println("Temperature is Off By :"+y2);
y1=(this.pressure) - (70);
y2=(70) - (this.pressure);
if(this.pressure > 70)

System.out.println("Pressure is Off By :"+y1);


else
System.out.println("Pressure is Off By :"+y2);
System.out.println("\n");
}
public Indicator(Observable observable) {// TODO Auto-generated
constructor stub
this.observable=observable;
observable.addObserver(this);
}
public void update(Observable o, Object arg) {
FurnaceData furnaceData=(FurnaceData)o;
this.pressure=furnaceData.getPressure();
this.temperature=furnaceData.getTemperature();
display();
}
}
FurnaceStation.java
public class FurnaceStation {
public static void main(String[] args) {
// TODO Auto-generated method stub
FurnaceData fd=new FurnaceData();
HeatingControll hc=new HeatingControll(fd);
Indicator id=new Indicator(fd);
LogData ld=new LogData(fd);
fd.setMeasurements(180f,30.4f);
fd.setMeasurements(80f,130.4f);
}
}

LogData.java
import java.util.Observable;
import java.util.Observer;
public class LogData implements Observer {
private float temperature;
public Object observable;
public void display() {// TODO Auto-generated method stub
System.out.println("\nLog Data");
System.out.println("Current Temperature is :"+temperature);
System.out.println("Current Pressure is :"+pressure);
System.out.println("\n");
}
public LogData(Observable observable) {// TODO Auto-generated
constructor stub
this.observable=observable;
observable.addObserver(this);
}
public void update(Observable o, Object arg) {
FurnaceData furnaceData=(FurnaceData)o;
this.pressure=furnaceData.getPressure();
this.temperature=furnaceData.getTemperature();
display();

}
}
FurnaceData.java
import java.util.Observable;
public void setMeasurements(float temp,float p) {
this.temperature = temp;
this.pressure=p;
this.measurementChanged();
}
public void measurementChanged() {// TODO Auto-generated method
stub
this.setChanged();
this.notifyObservers();
}
}
HeatingControl.java
import java.util.Observable;
import java.util.Observer;
public class HeatingControll implements Observer {
public void display() {
System.out.println("\nHeating Controll Data");
if(this.temperature > 100)
System.out.println("Temperature is more than 100");
else
System.out.println("Temperature is less than 100");
if(this.pressure > 70)
System.out.println("Pressure is more than 70");
else
System.out.println("Pressure is less than 70");
}
public HeatingControll(Observable observable) {
this.observable=observable;
observable.addObserver(this);
}
public void update(Observable o, Object arg) {
FurnaceData furnaceData=(FurnaceData)o;
this.pressure=furnaceData.getPressure();
this.temperature=furnaceData.getTemperature();
display();
}
}
OUTPUT
Log Data
Current Temperature is :180.0
Current Pressure is :30.4
Indicator Data
Temperature is Off By :80.0
Pressure is Off By :39.6
Heating Controll Data
Temperature is more than 100

Pressure is less than 70


Log Data
Current Temperature is :80.0
Current Pressure is :130.4
Indicator Data
Temperature is Off By :20.0
Pressure is Off By :60.399994
Heating Controll Data
Temperature is less than 100
Pressure is more than 70

4.Command Processor Pattern


Pattern Instance

Class Diagram

Implementation
Person.java

public class Person {


public void invoke() {
TextEditor aReceiver = new TextEditor();
Bold aConcreteCommand = new Bold(aReceiver);
InputDevice anInvoker = new InputDevice();
anInvoker.setCommand(aConcreteCommand);
anInvoker.invokeCommand();
}
public static void main(String[] arg)
{
InputDevice id=new InputDevice();
TextEditor ed=new TextEditor();
Bold bd=new Bold(ed);
Uppercase uc=new Uppercase(ed);
Undo un=new Undo(ed);
id.setCommand(bd);
id.setCommand(uc);
id.setCommand(un);
for(int i=0;i<arg.length;i++)
{
if(arg[i].equals("bold"))
{
id.BoldClicked();
}
else if(arg[i].equals("uppercase"))
{
id.UppercaseClicked();

}
else if(arg[i].equals("undo"))
{
id.UndoClicked();
}
else
{
System.out.println("Invalid Choice");
}
}
}

InputDevice.java
public class InputDevice {
private Command command;
TextEditor d=new TextEditor();
public void BoldClicked()
{
d.Bold();
}
public void UppercaseClicked()
{
d.Uppercase();
}
public void UndoClicked()
{
d.undo();
}
}
TextEditors.java
public class TextEditor {
public void Bold()
{
System.out.println("Text Command:Bold");
}
public void Uppercase()
{
System.out.println("Text Command:Uppercase");
}
public void undo()
{
System.out.println("Text Command:Undo");
}
}
5.Forward-Receiver
Pattern Instance

Class Diagram

Implementation
mainclass.java
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
Forwarder f1=new Forwarder();
Forwarder f2=new Forwarder();
Receiver r1=new Receiver();
Receiver r2=new Receiver();
Peer p1=new Peer("Peer 1");
Peer p2=new Peer("Peer 2");
p1.setForwarder(f1);
p2.setForwarder(f2);
p1.setReceiver(r1);
p2.setReceiver(r2);
Scanner s=new Scanner(System.in);
System.out.println("Enter Message To Send");
String msg=s.next();
System.out.println("Enter Message To Send");
msg=s.next();
System.out.println("\n\n");

p1.service(msg,p2);
System.out.println("\n");
p2.service(msg,p1);
}
}
Peer.java
public class Peer {
String name;
public Peer(String a) {
name=a;
}
public Receiver receiver;
public Forwarder forwarder;
public void service(String msg,Peer dest) {
System.out.println("Sending Message To Destination :"+dest);
this.forwarder.sendMsg(msg, dest, this);
}
}
Receiver.java
public class Receiver {
public Peer peer;
public Peer getPeer() {
return peer;
}
public Forwarder forwarder;
public void receiveMsg(String msg,Peer src) {
String newmsg;
newmsg=msg.substring(3,msg.length()-4);
System.out.println("\nMessage Received From Peer:"+src);
System.out.println("Message is:"+msg);
System.out.println("Unmarshalled Message is:"+newmsg);
}
}
Forarder.java
public class Forwarder {
public Peer peer;
public Receiver receiver;
public void sendMsg(String msg,Peer dest,Peer src) {
String newmsg;
newmsg=msg.concat("abcd");
newmsg= "xyz"+newmsg;
System.out.println("Marshalled Msg: "+newmsg);
Receiver rt=dest.getReceiver();
rt.receiveMsg(newmsg,src);
}
}
6.Client-Dispatcher
Pattern Instance

Class Diagram

Implementation
Client.java
public class Client {
public Server server;
public PrintService printService;
public Dispatcher dispatcher;
public void doTask() {// TODO Auto-generated method stub
Server s;
try{
s=CDS.disp.locateServer("printserver1");
s.runService();
}

catch(Exception ex)
{
System.out.println("Server Not Found");
}
try{
s=CDS.disp.locateServer("printserver3");
s.runService();
}
catch(Exception ex)
{
System.out.println("Server Not Found");
}
}
PrintService.java
public class PrintService extends Server{
public PrintService(String srv,String svc)
{
super(srv,svc);
}
public Client client;
public Dispatcher dispatcher;
public void runService() {// TODO Auto-generated method stub
System.out.println("Service : " + super.getNameofservice()+" Ran
By :"+getNameofserver());
}
}
Dispatcher.java
import java.util.*;
class NotFound extends Exception
{
private static final Long serialVersionUID=1L;
}
public class Dispatcher {
public Hashtable registry=new Hashtable();
private Random rnd=new Random(123456);
public Client client;
public PrintService printService;
private Client clienT;
private PrintService PrintService;
public void registerService(String svc,Server obj) {
Vector v=(Vector)registry.get(svc);
if(v==null)
{
v=new Vector();
registry.put(svc,v);
}
v.addElement(obj);
}
public Server locateServer(String svc) {
Vector v=(Vector)registry.get(svc);
if(v==null || v.size()==0)
{
try
{
throw new NotFound();
}
catch (NotFound e) {

//System.out.println("Server Not Found");

}
int i=(rnd.nextInt()%(v.size()));
return (Server)v.elementAt(i);

}
}
Server.java
public abstract class Server {
public String nameofservice;
public String nameofserver;
private Dispatcher dispatcher;
public Server(String svc,String srv)
{
nameofservice=svc;
nameofserver=srv;
CDS.disp.registerService(nameofservice, this);
}
public Client client;
}
CDS.java
public class CDS extends PrintService{
public CDS(String srv,String svc)
{
super(srv,svc);
}
public static Dispatcher disp;
}
public static void main(String[] args) {
disp=new Dispatcher();
Client c1=new Client();
try{
Server svc=new PrintService("printserver1","server1");
Server svc1=new PrintService("printserver34","server3");
c1.doTask();
}
catch (Exception e) {
System.out.println("Not Found");
}
}
}

7.Proxy
Pattern Instance

Class Diagram

Implementation
Application.java
public class Application {
private ProxyEmailService proxyemailservice;
private Customer customer;
public EmailService locateService()
{
EmailService s=new RealEmailService();
return s;
}
}
Customer.java
public class Customer {
private Application application;
public static void main(String[] arg)
{
Application app=new Application();
EmailService es=app.locateService();
es.sendmail("abc@gmail.com","Hello","Text1");
es.recvmail("xyz@gmail.com");
}
}
EmailService.java
public interface EmailService {
public void sendmail(String recv,String subject,String text);
public void recvmail(String recv);
}

ProxyEmailService.java
public class ProxyEmailService implements EmailService {
private RealEmailService realSubject;
private Application application;
public ProxyEmailService(RealEmailService realSubject) {
this.realSubject = realSubject;
}
private RealEmailService realemailservice;
public void sendmail(String recv,String subject,String text)
{
if(realemailservice==null)
{
realemailservice=new RealEmailService();}
realemailservice.sendmail(recv,subject,text);
}
public void recvmail(String recv)
{
if(realemailservice==null)
{
realemailservice=new RealEmailService();}
realemailservice.recvmail(recv);
}
}

RealEmailService.java

public class RealEmailService implements EmailService {


public void sendmail(String recv,String subject,String text)
{
System.out.println("Sending message to "+recv+"with
subject"+subject+"\nText:"+text);
}
public void recvmail(String recv)
{
System.out.println("Received message from "+recv);
}
}

8.Facade
Pattern Instance

Class Diagram

Implementation
Amplifier.java

public class Amplifier {


private String description;
private DvdPlayer Dvd;
public DvdPlayer getDvd() {
return Dvd;
}
public Amplifier(String description) {
this.description = description;
}
public void on() {// TODO Auto-generated method stub
System.out.println(description +"ON");
}
public void off() {// TODO Auto-generated method stub
System.out.println(description +"OFF");
}
public String toString() {
return description;// TODO Auto-generated method stub
}
}

DVDPlayer.java

public class DvdPlayer {


private String description,movie;
private Amplifier amplifier;
public DvdPlayer(String description, Amplifier amplifier) {
this.description =description;

this.amplifier=amplifier;
}
public void on() {// TODO Auto-generated method stub
System.out.println(description +"On");
}
public void off() {// TODO Auto-generated method stub
System.out.println(description +"OFF");
}
public void play(String movie) {// TODO Auto-generated method stub
this.movie = movie;
System.out.println(description +"Playing"+" Movie:"+movie);
System.out.println();
}
public void stop() {// TODO Auto-generated method stub
System.out.println(description +"Playing"+" Movie:"+movie);
}
public String toString() {// TODO Auto-generated method stub
return description;
}
}

HomeThetreSystem.java

public class HomeTheaterSystem {


private Amplifier amplifier;
Projector prj;
private Amplifier amp;
private DvdPlayer Dvd;
public HomeTheaterSystem(Amplifier amp,DvdPlayer dvd,Projector prj) {
this.amp=amp;
this.Dvd=dvd;
this.prj=prj;
}
public void WatchMovie(String movie) {
System.out.println("Home Theartre On");
prj.on();
amp.on();
Dvd.on();
Dvd.play(movie);
}
public void EndMovie() {// TODO Auto-generated method stub
System.out.println("Home Theartre Off");
prj.off();
amp.off();
Dvd.stop();
Dvd.off();
}
}

HomeThetreSystemFascade.java

public class HomeTheatreSystemFascade {


public static void main(String[] args) {
Amplifier amp=new Amplifier("Apple Amplifier");
DvdPlayer dvd=new DvdPlayer("Apple DvD Player",amp);
Projector prj=new Projector("Apple Projector",dvd);
HomeTheaterSystem hts=new HomeTheaterSystem(amp,dvd,prj);
hts.WatchMovie("Steve Jobs:Documentary");

hts.EndMovie();

Projector.java

public class Projector {


private String description;
private DvdPlayer DvdPlayer;
public Projector(String description,DvdPlayer dvdplayer) {
this.description=description;
this.DvdPlayer=dvdplayer;
}
public void on() {// TODO Auto-generated method stub
System.out.println(description +"On");
}
public void off() {// TODO Auto-generated method stub
System.out.println(description +"OFf");
}
public void tvmode() {// TODO Auto-generated method stub
System.out.println(description +"Tv Mode");
}
public String toString() {// TODO Auto-generated method stub
return description;
}
}

9.Polymorphism
Pattern Instance

Class Diagram

Implementation
Ishape.java
public interface Ishape {
public void area();
public void name();
}

//coded
//coded

mainclass.java

import java.util.Scanner;
public class mainclass { //page coded
public static void main(String[] args) {
Circle c=new Circle();
Triangle t=new Triangle();
Scanner s=new Scanner(System.in);
System.out.println("Enter the radius of Circle");
c.setRadius(s.nextDouble());
System.out.println("Enter the base & height");
double b=s.nextDouble();
double h=s.nextDouble();
t.setsize(b, h);
c.name();
c.area();
t.name();
t.area();
}
}

Circle.java

public class Circle implements Ishape {


private Double Pi=3.142; //coded
private Double Area;
private Double Radius;
public void name() {// fun coded

System.out.println("The Shape Is Circle");


}
public void area() {// fun coded
double area=Pi * Radius * Radius;
System.out.println("Area Of Circle : "+area+" sq.units");
}
}

Triangle.java

public class Triangle implements Ishape {


private Double Base;
private Double Height;
private Double Area;
public void setsize(Double b,Double h) {// fun coded
this.Base =b;
this.Height=h;
}
public void name() {// fun coded
System.out.println("The Shape Is Triangle");
}
public void area() {// coded
double area=(Base * Height)/2;;
System.out.println("Area Of Triangle : "+area+" sq.units");
}
}

10.Composite Pattern(whole part)


Pattern Instance

Class Diagram

Implementation
Application.java
import java.util.*;
public class Application {
public static void main(String[] args) {
List items=new ArrayList();
String cd;
double price;
Scanner s=new Scanner(System.in);
System.out.println("Enter number of Family Packs");
int n=s.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("Enter name of ColdDrink & price");
cd=s.next();
price=s.nextDouble();
items.add(new ColdDrink(cd,"Cold Drink",price));
}
ColdDrinkFamilyPack familypack=new ColdDrinkFamilyPack(items);
//
items.add(new ColdDrink("Coke","Cold Drink",20));
//
items.add(new ColdDrink("Maza","Cold Drink",15));
List item2=new ArrayList();
/*
item2.add(new ColdDrink("Coke","Cold Drink",20));
item2.add(new ColdDrink("Maza","Cold Drink",15));
item2.add(new ColdDrink("Pepsi","Cold Drink",10));
item2.add(new ColdDrink("Coke","Cold Drink",20));
item2.add(new ColdDrink("Maza","Cold Drink",15));
*/
System.out.println("Enter number of Party Packs");
n=s.nextInt();

for(int i=0;i<n;i++)
{
System.out.println("Enter name of ColdDrink & price");
cd=s.next();
price=s.nextDouble();
item2.add(new ColdDrink(cd,"Cold Drink",price));
}
ColdDrinkPartyPack partypack=new ColdDrinkPartyPack(items);
System.out.println("Discount for Cold Drink Family Pack");
System.out.println(familypack.getPrice());
System.out.println("Discount for Cold Drink Party Pack");
System.out.println(partypack.getPrice());
}

ColdDrinkFamilyPack.java
import java.util.List;
public class ColdDrinkFamilyPack extends Composite {
public ColdDrinkFamilyPack(List items)
{
super.addItems(items);
}
public double getPrice() {// TODO Auto-generated method stub
return (super.getPrice() - super.getPrice() * .15);
}
}

ColdDrinkFamilyParty.java

import java.util.List;
public class ColdDrinkPartyPack extends Composite {
public ColdDrinkPartyPack(List items) {
super.addItems(items);
}
public double getPrice() {// TODO Auto-generated method stub
return (super.getPrice() - super.getPrice() * .25);
}
}

ColdDrink.java

public class ColdDrink extends Item {


public String itemName,itemDesc;
public ColdDrink(String itemName,String desc,double price) {
this.itemName=itemName;
this.itemDesc=desc;
this.price=price;
}
private String name;
private String description;
private Double price;
}

Composite.java
import java.util.ArrayList;
import java.util.List;
public class Composite extends Item {
private Object ItemName;
List<Item> items=new ArrayList<Item>();

public void add(Item itm) {// TODO Auto-generated method stub


items.add(itm);
}
public void addItems(List list) {// TODO Auto-generated method stub
items.addAll(list);
}
public double getPrice() {// TODO Auto-generated method stub
double sum=0;
for(Item i:items)
{
sum+=i.getPrice();
}
return sum;
}
public synchronized void addChild(Item a_component) {
synchronized (a_component) {
m_children.add(a_component);
a_component.setParent(this);
}
}
public synchronized void removeChild(Item a_component) {
synchronized (a_component) {
if (this == a_component.getParent()) {
a_component.setParent(null);
}
m_children.remove(a_component);
}
}
}
Item.java
public abstract class Item {
public abstract void Operation();
public abstract double getPrice();
public void setQuantity() {// TODO Auto-generated method stub
}
private Item m_parent;
public Item getParent() {
return m_parent;
}
public void setParent(Item a_parent) {
m_parent = a_parent;
}
public abstract Composite getComposite();
}
11.Master-Slava
Pattern Instance

Class Diagram

Implementation
mainMaster.java
public class mainMaster {
public static void main(String[] args) {
Master master =new Master();
master.run();
}
}
Master.java
public class Master {
private Resource resource;
private Resource res=new Resource();
private int slaveCount=2;
private Slave[] slaves=new Slave[slaveCount];
public void run()
{
for(int i=0;i<slaveCount;i++)
{
slaves[i]=new Slave(res);
}

for(int i=0;i<slaveCount;i++)
{
slaves[i].start();
}
for(int i=0;i<slaveCount;i++)
{
try{
slaves[i].join();
}
catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
finally{
System.out.println(slaves[i].getName()+" has died");
}
}
System.out.println("The masters will now die...");
}
}
Resource.java
public class Resource {
private TestMaster testmaster;
private int status=0;
public synchronized int incStatus()
{
int local=status;
System.out.println("status="+local);
local++;
try{
Thread.sleep(50);
}
catch(Exception e){}
status=local;
System.out.println("now Status="+local);
return status;
}
private Master master;
private Slave slave;
public Slave getSlave() {
return slave;
}
public void setSlave(Slave theSlave) {
slave = theSlave;
}
}
Slave.java
public class Slave extends Thread {
private Resource resource;
private Resource sharedResource;
private boolean done=false;
public void halt()

done=true;

}
public Slave(Resource res)
{
sharedResource=res;
}
protected boolean task()
{
int status=sharedResource.incStatus();
return (status>=20);
}
public void run()
{
while(done!=true){
done=task();
try
{
Thread.sleep(500);
}
catch(Exception e)
{
}
}

}
TestMaster.java
public class TestMaster {
private Resource resource;
public Resource getResource() {
return resource;
}
public static void main() {
}
}