0% found this document useful (0 votes)
74 views

Câu 5. Ví dụ về một số Pattern. 1; Adapter

The document provides examples of design patterns including Adapter, Bridge, Facade, and Decorator patterns. It also provides examples of different types of beans in J2EE including stateless session beans and stateful session beans used in a banking application.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Câu 5. Ví dụ về một số Pattern. 1; Adapter

The document provides examples of design patterns including Adapter, Bridge, Facade, and Decorator patterns. It also provides examples of different types of beans in J2EE including stateless session beans and stateful session beans used in a banking application.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 28

Cu 5. V d v mt s Pattern.

1; Adapter

PrintString.java(Adaptee) : package org.arpit.javapostsforlearning.designpatterns; public class PrintString { public void print(String s) { System.out.println(s); } }

PrintableList.java(Target) package org.arpit.javapostsforlearning.designpatterns; import java.util.ArrayList; public interface PrintableList { void printList(ArrayList<String> list); }

PrintableListAdapter.java(Adapter) package org.arpit.javapostsforlearning.designpatterns; import java.util.ArrayList; public class PrintableListAdapter implements PrintableList{ public void printList(ArrayList<String> list) { //Converting ArrayList<String> to String so that we can pass String to // adaptee class String listString = ""; for (String s : list) { listString += s + "\t"; } // instantiating adaptee class PrintString printString=new PrintString(); ps.print(listString); } }

AdapterDesignPatternMain.java package org.arpit.javapostsforlearning.designpatterns; import java.util.ArrayList; public class AdapterDesignPatternMain { public static void main(String[] args) { ArrayList<String> list=new ArrayList<String>(); list.add("one"); list.add("two"); list.add("three"); PrintableList pl=new PrintableListAdapter();

pl.printList(list); } }

Output one two three

2; Bridge

Abstraction Interface public interface Persistence { /** * @param object * @return returns objectID */ public String persist(Object object); /** * * @param objectId * @return persisted Object */ public Object findById(String objectId); /** *

* @param id */ public void deleteById(String id); }

Abstraction Imp public class PersistenceImp implements Persistence { private PersistenceImplementor implementor = null; public PersistenceImp(PersistenceImplementor imp) { this.implementor = imp; } @Override public void deleteById(String id) { implementor.deleteObject(Long.parseLong(id)); } @Override public Object findById(String objectId) { return implementor.getObject(Long.parseLong(objectId)); }

@Override public String persist(Object object) { return Long.toString(implementor.saveObject(object)); }

} Implementor Interface public interface PersistenceImplementor { public long saveObject(Object object); public void deleteObject(long objectId); public Object getObject(long objectId); } Concrete Implementor public class FileSystemPersistenceImplementor implements PersistenceImplementor{ @Override public void deleteObject(long objectId) { File f = new File("/persistence/"+Long.toString(objectId)); f.delete(); return; } @Override public Object getObject(long objectId) { File f = new File("/persistence/"+Long.toString(objectId)); return readObjectFromFile(f); }

private Object readObjectFromFile(File f) { // open file // and load object //return the object return null; } @Override public long saveObject(Object object) { long fileId = System.currentTimeMillis(); // open file File f = new File("/persistence/"+Long.toString(fileId)); // write file to Streanm writeObjectToFile(f,object); return fileId; } private void writeObjectToFile(File f, Object object) { // serialize object and write it to file } } Database concrete implementor

public class DabatasePersistenceImplementor implements PersistenceImplementor{ public DabatasePersistenceImplementor() {

// load database driver } @Override public void deleteObject(long objectId) { // open database connection // remove record } @Override public Object getObject(long objectId) { // open database connection // read records // create object from record return null; } @Override public long saveObject(Object object) { // open database connection // create records for fields inside the object return 0; } }

public class PersistenceFrameworkDriver { public static void main(String[] args) { // this program needs a persistence framework // at runtime an implementor is chosen between file system implementation and //database implememtor , depending on existence of databse

drivers

PersistenceImplementor implementor = null; if(databaseDriverExists()){ implementor = new DabatasePersistenceImplementor(); }else{ implementor = new FileSystemPersistenceImplementor(); } Persistence persistenceAPI = new PersistenceImp(implementor); Object o = persistenceAPI.findById("12343755"); // do changes to the object // then persist persistenceAPI.persist(o); // can also change implementor persistenceAPI = new PersistenceImp(new DabatasePersistenceImplementor()); persistenceAPI.deleteById("2323"); } private static boolean databaseDriverExists() { return false; } }

3; Faade Class1 package com.cakes; public class Class1 { public int doSomethingComplicated(int x) { return x * x * x; } } Class2 package com.cakes; public class Class2 { public int doAnotherThing(Class1 class1, int x) { return 2 * class1.doSomethingComplicated(x); } } Class3 package com.cakes; public class Class3 { public int doMoreStuff(Class1 class1, Class2 class2, int x) { return class1.doSomethingComplicated(x) * class2.doAnotherThing(class1, x); } }

Facade package com.cakes; public class Facade { public int cubeX(int x) { Class1 class1 = new Class1(); return class1.doSomethingComplicated(x); } public int cubeXTimes2(int x) { Class1 class1 = new Class1(); Class2 class2 = new Class2(); return class2.doAnotherThing(class1, x); } public int xToSixthPowerTimes2(int x) { Class1 class1 = new Class1(); Class2 class2 = new Class2(); Class3 class3 = new Class3(); return class3.doMoreStuff(class1, class2, x); } } FacadeDemo package com.cakes; public class FacadeDemo { public static void main(String[] args) { Facade facade = new Facade(); int x = 3; System.out.println("Cube of " + x + ":" + facade.cubeX(3)); System.out.println("Cube of " + x + " times 2:" + facade.cubeXTimes2(3)); System.out.println(x + " to sixth power times 2:" + facade.xToSixthPowerTimes2(3));

} } 4; Decorator

Icecream package com.javapapers.sample.designpattern; public interface Icecream { public String makeIcecream(); } SimpleIcecream package com.javapapers.sample.designpattern; public class SimpleIcecream implements Icecream {

@Override public String makeIcecream() { return "Base Icecream"; } } IcecreamDecorator package com.javapapers.sample.designpattern; abstract class IcecreamDecorator implements Icecream { protected Icecream specialIcecream; public IcecreamDecorator(Icecream specialIcecream) this.specialIcecream = specialIcecream; } public String makeIcecream() { return specialIcecream.makeIcecream(); } } NuttyDecorator package com.javapapers.sample.designpattern; public class NuttyDecorator extends IcecreamDecorator { public NuttyDecorator(Icecream super(specialIcecream); }
specialIcecream) { {

public String makeIcecream() { return specialIcecream.makeIcecream() } private String addNuts() { return " + cruncy nuts";

+ addNuts();

} } HoneyDecorator package com.javapapers.sample.designpattern; public class HoneyDecorator extends IcecreamDecorator { public HoneyDecorator(Icecream specialIcecream) { super(specialIcecream); } public String makeIcecream() { return specialIcecream.makeIcecream() + addHoney(); } private String addHoney() { return " + sweet honey"; } } TestDecorator package com.javapapers.sample.designpattern; public class TestDecorator { public static void main(String args[]) { Icecream icecream = new HoneyDecorator(new NuttyDecorator(new System.out.println(icecream.makeIcecream()); } } Output Base Icecream + cruncy nuts + sweet honey

SimpleIcecream()));

Cu 6. Vi d v cc dng bean trong J2EE 1. Staless session bean Home Interface import javax.ejb.*; import java.rmi.RemoteException; public interface HelloHome extends EJBHome { Hello create() throws RemoteException, CreateException; }

Remote Interface import javax.ejb.*; import java.rmi.RemoteException; import java.rmi.Remote; public interface Hello extends EJBObject { public String hello() throws java.rmi.RemoteException; } Bean Class public class HelloBean implements SessionBean { // these are required session bean methods public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext ctx) {} // this is our business method to be called by the client public String hello() { return Hello, world!; } } EJB Client

public class HelloClient { public static void main(String[] args) { try { InitialContext ic = new InitialContext(); Object objRef = ic.lookup("java:comp/env/ejb/Hello"); HelloHome home = (HelloHome)PortableRemoteObject.narrow(objRef, HelloHome.class); Hello hello = home.create(); System.out.println( hello.hello() ); hello.remove(); } catch (Exception e) { e.printStackTrace(); } } }

2. Staful session bean - V d: ng dng account s dng Stateful Session Bean th hin hai hnh ng giao dch cho khch hng. Remote business interface (Account) package ejbExample.stateful; import javax.ejb.Remote; @Remote public interface Account { public float deposit(float amount); public float withdraw(float amount); @Remove public void remove(); }

Session bean class (AccountBean) package ejbExample.stateful; import javax.ejb.Stateful; import javax.ejb.Remote; import javax.ejb.Remove; import javax.ejb.*; @Stateful(name="AccountBean") @Remote(AccountRemote.class) public class AccountBean implements AccountRemote { float balance = 0; public float deposit(float amount){ balance += amount; return balance; } public float withdraw(float amount){ balance -= amount; return balance; } @Remove public void remove() { balance = 0; } }

@Remove public void remove() { balance = 0;

Cu 9: Trnh by thit k kin trc ca H qun l th vin Mt kin trc thit k tt s l nn tng cho mt h thng c kh nng m rng v d dng bo tr. C th ni rng ngi to ra kin trc l ngi ng vai tr quan trng nht trong hu ht cc d n, h thc hin vic thit k theo c chiu rng v chiu su ca kin trc. Nhng th nh l key package, cu trc lp, la chn hoc thit k cc thnh phn c th ti s dng vi quy m ln, lp li cc chc nng (v d nh m hnh bo mt), v gip cc thit k v tiu chun lp trnh c duy tr trong sut vng i ca d n l nhng v d v trch nhim trong kin trc. Cu trc h thng Cc package cung cp cc lp cho H qun l th vin: Presentation: package ny cha cc lp cho ton b giao din ngi dng, cho php ngi dng xem d liu t h thng v nhp d liu mi. Cc tiu chun trnh by nhng thng tin ny ti ngi dng trong mt ng dng Java Web l JSP. Cc package ny lin kt vi cc i tng nghip v (thng qua Value Objects) v cc package iu khin. Cc package giao din ngi dng s dng cc Value Objects gi d liu bi vy n c th c gi ti cc package iu khin. Controller: Cc lp trong package ny chu trch nhim cho hu ht cc ng dng iu khin v cng cung cp cc c ch traffic cop tch bit cc s ph thuc gia presentation v domain package. Business: package ny bao gm cc lp min t m hnh phn tch nh: Borrower, Title, Item, Loan, Nhng lp ny c chi tit ha trong phn thit k t cc phng thc ca chng s c nh ngha c th. Cc package i tng nghip v lin kt vi package c s d liu thng qua mt mi quan h kt hp. Dao: c t tn l dao bi v n cha mt i tng truy cp d liu (Data Access Object) i din cho mt mu thit k thng c s dng, cc mu thng ng gi tt c nhng phng thc c lin quan n d liu vo nhng lp ri rc. iu ny c ngha i vi tng la hoc gii hn hiu bit v s tn ti ca mi vt.

Vo: package vo cha cc Value Object n gin, nhng th lin quan n tn min. Cc Value Object l mt m hnh ph bin c s dng hn ch vic thng qua cc i tng heavyweight v lu lng truy cp trn h thng doanh nghip.

M hnh lp ngn gn

M hnh lp chi tit nu ln cu trc tng qut ca h qun l th vin Cc c ch kin trc Cc c ch kin trc m t cc k thut x l nh: persistence, security, error handling, system interfaces. C ch kin trc phi c m hnh ha cung cp cho cc kin trc s v cc nh pht trin mt ci nhn v cc c ch ph bin c s dng trong bt k mt use case no. Cc ng dng phi c cc i tng c lu tr lin tc, do mt lp c s d liu, c gi l package dao, phi c b sung cung cp dch v ny. Cc gii php cho mt ng dng phc tp l s dng mt c s d liu thng mi, in hnh l H thng qun l c s d liu quan h (RDBMS) nh Oracle hoc

SQL Server. Tuy nhin, bi v ng dng ny c thit k c tnh di ng, nn ta chn c s d liu m ngun m l MySQL. D liu c thao tc bng cch s dng cc DAO, ci t cc giao din ph bin gi cc phng thc ph bin nh creat(), store(), remove(), v load() trn cc i tng. Cc mu thit k Cc mu thit k l cc gii php c chng minh, c th ti s dng, c dng gii quyt mt vn c th.Trong khi thit k bi ton, cc mu c s dng trong ng dng ny: Model-View-Control (MVC): M hnh ny bao gm cc d liu nghip v, giao din (JSP,) th hin ni dung ca m hnh, v phn iu khin nh ngha ra cc hnh vi ca ng dng. Front Controller: M hnh ny cung cp im kt ni u tin x l cc yu cu c gi n cho ng dng. Data Access Object (DAO): M hnh ny c s dng tru tng ha v ng gi tt c cc truy cp ti ngun d liu, tc ng ti d liu m khng lm nh hng ti cc lp nghip v. Value Object (VO): c s dng ng gi d liu nghip v bi cc i tng nghip v, cc DAO v JSP.

Biu tun t

V d:

Biu lp vi DAO v VO

You might also like