java_JAVA常用设计模式.pdf
Java?Lesson 1?Factory-?.?,?.?.?,?.?Factory-?MM?,?MM?,?,?MM?,?.?Factory?Factory-?public class Factory public static Sample creator(int which)/getClass?Sample?.if(which=1)return new SampleA();else if(which=2)return new SampleB();?FACTORY METHOD-?,?,?,?,?.?FACTORY METHOD-?MM?,?MM?,?,?Factory Method?,?MM?,?,?,?MM?.?FACTORY METHOD-?public abstract class Factory public abstract Sample creator();public abstract Sample2 creator(String name);public class SimpleFactory extends Factory public Sample creator()return new SampleA public Sample2 creator(String name)return new Sample2A public class BombFactory extends Factory public Sample creator()return new SampleB public Sample2 creator(String name)return new Sample2B?Builder?Builder-?,?.?,?.?.?Builder?Builder-?MM?,?MM,?,?,?,?MM?,?,?MM?,?builder.(?)?Builder?Builder-?public interface Builder /?A?void buildPartA();/?B?void buildPartB();/?C?void buildPartC();/?(?)/?,?Director?./?Product getResult();public class Director private Builder builder;public Director(Builder builder)this.builder=builder;/?partA partB partC?/?public void construct()builder.buildPartA();builder.buildPartB();builder.buildPartC();?PROTOTYPE?PROTOTYPE-?,?.?,?,?.?.?PROTOTYPE?PROTOTYPE-?MM?QQ?,?,?,?copy?QQ?,?prototype?.(100?,?)?PROTOTYPE?PROTOTYPE-?public abstract class AbstractSpoon implements Cloneable String spoonName;public void setSpoonName(String spoonName)this.spoonName=spoonName;public String getSpoonName()return this.spoonName;public Object clone()Object object=null;try object=super.clone();catch(CloneNotSupportedException exception)System.err.println(AbstractSpoon is not Cloneable);return object;public class SoupSpoon extends AbstractSpoon public SoupSpoon()setSpoonName(Soup Spoon);public class SaladSpoon extends AbstractSpoon public SaladSpoon()setSpoonName(Salad Spoon);?Singleton-?,?.?.?Singleton-?6?,?,?Sigleton,?,?,?(?,?)?Singleton-?public class Singleton private static Singleton instance=null;public static synchronized Singleton getInstance()/?,?,?/?,?!if(instance=null)instance=new Singleton();return instance;?Adapter?Adapter-?,?.?.?Adapter?Adapter-?Sarah,?,?,?,?kent?,?Sarah?Adapter,?Sarah?(?)?Adapter?Adapter-?public interface IRoundPeg public void insertIntoHole(String msg);public interface ISquarePeg public void insert(String str);public class PegAdapter implements IRoundPeg,ISquarePeg private RoundPeg roundPeg;private SquarePeg squarePeg;/?public PegAdapter(RoundPeg peg)this.roundPeg=peg;/?public PegAdapter(SquarePeg peg)(this.squarePeg=peg;)public void insert(String str)roundPeg.insertIntoHole(str);public void insertIntoHole(String str)SquarePeg.insert(str);?Bridge?Bridge-?,?,?,?/?,?.?Bridge?Bridge-?MM,?,?MM,?;?MM?,?,?MM?,?.?MM?,?BRIDGE?Bridge?Bridge-?public abstract class Coffee CoffeeImp coffeeImp;public void setCoffeeImp()this.CoffeeImp=CoffeeImpSingleton.getTheCoffeImp();public SodaImp getCoffeeImp()return this.CoffeeImp;public abstract void pourCoffee();public abstract class CoffeeImp public abstract void pourCoffeeImp();/bridge public class CoffeeImpSingleton private static CoffeeImp coffeeImp;public CoffeeImpSingleton(CoffeeImp coffeeImpIn)this.coffeeImp=coffeeImpIn;public static CoffeeImp getTheCoffeeImp()return coffeeImp;?Composite?Composite-?,?.?.?.?.?Composite?Composite-?Mary?.?,?.?,?,?,?.?T?,?,?,?,?,?.?,?,?.?,T?,?,?,?.,MM?Composite?,?Composite?Composite-?public abstract class Equipment private String name;/?public abstract double netPrice();/?public abstract double discountPrice();/?public boolean add(Equipment equipment)return false;/?public boolean remove(Equipment equipment)return false;/?,?.public Iterator iter()return null;public Equipment(final String name)this.name=name;public class Disk extends Equipment abstract class CompositeEquipment extends Equipment?DECORATOR?DECORATOR-?,?,?.?,?.?.?DECORATOR?DECORATOR-?Mary?Sarly?,?,?,?,?,?Fita,?(?MM?),?Mike?,?Decorator,?,?,?DECORATOR?DECORATOR-?public interface Work public void insert();public class SquarePeg implements Work public void insert()System.out.println(?);public class Decorator implements Work private Work work;/?List?private ArrayList others=new ArrayList();/?new?,?Work?;public Decorator(Work work)this.work=work;others.add(?);others.add(?);public void insert()newMethod();/?,?insert?,?public void newMethod()otherMethod();work.insert();public void otherMethod()ListIterator listIterator=others.listIterator();while(listIterator.hasNext()System.out.println(String)(listIterator.next()+?);?Facade?Facade-?.?,?.?,?,?.?.?Facade?Facade-?Nikon?,?,?,?,?MM?,?.?Facade?,?,?,?,?MM?.?Facade?Facade-?public class DBCompare String sql=SELECT*FROM WHERE =?;try Mysql msql=new mysql(sql);prep.setString(1,);rset=prep.executeQuery();if(rset.next()System.out.println(rset.getString(column name);catch(SException e)e.printStackTrace();finally mysql.close();mysql=null;?FLYWEIGHT?FLYWEIGHT-?FLYWEIGHT?.?.?.?,?.?.?,?.?,?.?,?.?.?FLYWEIGHT?FLYWEIGHT-?MM?,?,?,?,?,?,?MM?,?.?Flyweight,MM?,?.?FLYWEIGHT?FLYWEIGHT-?public class CD private String title;private int year;private Artist artist;public String getTitle()public int getYear()public Artist getArtist()return title;return year;return artist;public void setTitle(String t)title=t;public void setYear(int y)year=y;public void setArtist(Artist a)artist=a;public class Artist /?private String name;/note that Artist is immutable.String getName()return name;name=n;public class ArtistFactory Artist(String n)Hashtable pool=new Hashtable();Artist getArtist(String key)Artist result;result=(Artist)pool.get(key);/?Artist if(result=null)result=new Artist(key);pool.put(key,result);return result;?PROXY?PROXY-?,?.?.?,?,?.?.?,?,?,?.?PROXY?PROXY-?MM?,?hi,?,?,?,?Proxy?,?,?,?,?.?PROXY?PROXY-?public class ForumPermissions implements Cacheable public class ForumProxy implements Forum public class DbForum implements Forum,Cacheable?Chain?Chain of Responsibility-?,?.?,?.?,?.?:?.?.?Chain?Chain of Responsibility-?,?,?,?MM?,?,?Hi,?,?,?,?MM?,?,?!?Chain?Chain of Responsibility-?public interface Handler public void handleRequest(Request request);public class Request private String type;public Request(String type)this.type=type;public String getType()return type;public void execute()/request?public class ConcreteHandler implements Handler private Handler successor;public ConcreteHandler(Handler successor)this.successor=successor;public void handleRequest(Request request)if(request instanceof HelpRequest)/?Help?else if(request instanceof PrintRequst)request.execute();else/?successor.handle(request);?COMMAND?COMMAND-?.?,?.?,?,?,?,?.?.?COMMAND?COMMAND-?MM?,?,?,?,?.?,?COMMAND,?,?,?:?COMMAND,?,?.,?COMMAND?COMMAND-?public interface Command public abstract void execute();public class producer public static List produceRequests()List queue=new ArrayList();queue.add(new DomesticEngineer();queue.add(new Politician();queue.add(new Programmer();return queue;public class TestCommand public static void main(String args)List queue=Producer.produceRequests();for(Iterator it=queue.iterator();it.hasNext();)/?List?,?,?100%?,/?Command?.?Command(Command)it.next().execute();?INTERPRETER?INTERPRETER-?,?,?.?.?,?.?.?,?.?,?.?.?INTERPRETER?INTERPRETER-?MM?,?MM?,?,?,?MM?,?Interpreter,?.?INTERPRETER?INTERPRETER-?,?.?ITERATOR?ITERATOR-?.?,?.?,?.?.?,?.?.?ITERATOR?ITERATOR-?Mary,?.Mary:?,?:?,?Mary:?:?,?,?Mary:?:?,?,?Mary:?,?,?:?,?,?ITERATOR?ITERATOR-?Collection?public class TestCommand public static void main(String args)List queue=Producer.produceRequests();for(Iterator it=queue.iterator();it.hasNext();)/?List?,?,?100%?,/?Command?.?Command(Command)it.next().execute();?MEDIATOR?MEDIATOR-?,?.?.?,?.?.?.?,?.?MEDIATOR?MEDIATOR-?MM?,?,?,?,?,?,?OK?,?MM?.?MEDIATOR?MEDIATOR-?public interface Mediator public class ConcreteMediator implements Mediator /?.private ConcreteColleague1 colleague1=new ConcreteColleague1();private ConcreteColleague2 colleague2=new ConcreteColleague2();public class Colleague private Mediator mediator;public Mediator getMediator()return mediator;public void setMediator(Mediator mediator)this.mediator=mediator;public class ConcreteColleague1 public class ConcreteColleague2?MEMENTO?MEMENTO-?.?,?,?,?,?.?MEMENTO?MEMENTO-?MM?,?MM?,?MM?,?,?MM?,?.?MEMENTO?MEMENTO-?public class Originator private int number;private File file=null;public Originator()/?Memento public Memento getMemento()return new Memento(this);/?public void setMemento(Memento m)number=m.number;file=m.file;private class Memento implements java.io.Serializable private int number;private File file=null;public Memento(Originator o)number=o.number;file=o.file;?OBSERVER?OBSERVER-?,?.?,?,?.?OBSERVER?OBSERVER-?MM?MM?,tom?,?,?,?(?)?OBSERVER?OBSERVER-?public class product extends Observable private String name;private float price;public String getName()return name;public void setName()this.name=name;/?setChanged();notifyObservers(name);public class NameObserver implements Observer public void update(Observable obj,Object arg)private String name=null;if(arg instanceof String)name=(String)arg;/?name?System.out.println(NameObserver:name changet to+name);?STATE?STATE-?.?.?,?.?,?.?.?,?.?OBSERVER?OBSERVER-?MM?,?,?,?,?MM?,?MM?,?,?MM?,?,?MM?.?OBSERVER?OBSERVER-?publicclass BlueState extends State public void handlepush(Context c)/?push?blue?green;c.setState(new GreenState();public void handlepull(Context c)/?pull?blue?red;c.setState(new RedState();public abstract void getcolor()return(Color.blue)public class Context private Sate state=null;/?Color state?State state;/setState?state?setState?pulic void setState(State state)this.state=state;public void push()/?,?,?handlepush?,?state.handlepush(this);/?sample?state?,?getColor()Sample sample=new Sample(state.getColor();sample.operate();public void pull()state.handlepull(this);Sample2 sample2=new Sample2(state.getColor();sample2.operate();?STRATEGY?STRATEGY-?,?,?.?.?.?,?.?,?,?.?STRATEGY?STRATEGY-?MM?,?,?,?,?,?MM?,?MM?Strategy?.?STRATEGY?STRATEGY-?public abstract class RepTempRule protected String oldString=;public void setOldString(String oldString)this.oldString=oldString;protected String newString=;public String getNewString()return newString;public abstract void replace()throws Exception;public class test public void testReplace()/?.RepTempRule rule=new RepTempRuleOne();rule.setOldString(record);rule.replace();?TEMPLATE METHOD?TEMPLATE METHOD-?,?,?.?,?.?,?.?TEMPLATE METHOD?TEMPLATE METHOD-?MM?MM?(Template method),?,?,?(?);?TEMPLATE METHOD?TEMPLATE METHOD-?public abstract class Benchmark /*?*/public abstract void benchmark();/*?benchmark?*/public final long repeat(int count)if(count=0)return 0;else long startTime=System.currentTimeMillis();benchmark();long stopTime=System.currentTimeMillis();return stopTime-startTime;public class MethodBenchmark extends Benchmark /*?benchmark?*/public void benchmark()for(int i=0;i Integer.MAX_VALUE;i+)System.out.printtln(i=+i);for(int i=0;i count;i+)?VISITOR?VISITOR-?.?,?.?,?,?.?,?.?,?.?,?,?.?.?VISITOR?VISITOR-?,?MM?,?MM?,?,?,?Visitor,?MM?,?,?;?VISITOR?VISITOR-?public interface Visitable public void accept(Visitor visitor);public class ConcreteVisitor implements Visitor /?,?Collection?public void visitCollection(Collection collection)Iterator iterator=collection.iterator()while(iterator.hasNext()Object o=iterator.next();if(o instanceof Visitable)(Visitable)o).accept(this);public void visitString(String string)System.out.println(+string+);public void visitFloat(Float float)System.out.println(float.toString()+f);study happy,made by micky