创建型设计模式
创建模式是处理对象创建的设计模式,试图根据实际情况使用合适的方式创建对象;创建模式的主导思想为,将系统使用的具体类封装起来,隐藏这些具体类的实例创建和结合的方式。
创建型设计模式主要有:抽象工厂模式、工厂方法模式、生成器模式、对象池模式、原型模式、单例模式、延迟初始化模式
抽象工厂模式(Abstract Factory)
概念
1、意图:提供一个创建一系列相关或相互依赖对象的接口,而无须指定他们具体的类
2、结构:AbstractFactory声明一个创建抽象产品对象的操作接口
ConcreteFactory实现创建具体产品对象的操作。
AbstractProduct为一类产品对象声明一个接口
ConcreteProduct定义一个将被相应的具体工创建的产品对象,实现AbstractProduct接口
Client仅使用由AbstractFactory和AbstractProduct接口
3、适用性:一个系统要独立于它的产品的创建、组合和表示;一个系统要由多个产品系列中的一个来配置;当强调一系列产品对象的设计以便进行联合使用时;当提供一个产品类库,只想显示他们的接口而不是实现时。
历年真题
import java util.*;class Department{代码省略}interface IDepartment{void Insert(Department department); //考题1Department GetDepartment(int id); //考题2 }class SqlserverDepartment implements IDepartment {//implements IDepartment考题3public void Inesrt(Department department){System.out.println("Insert a record into Department in SQLServer!")}public Department GetDepartment (int id){代码省略}}class AccessDepartmentimplements IDepartment{ //implements IDpartment 考题4public void Insert (Department department){System.out.println("Insert a record into Department in ACCESS!")}public Department GetDepartment (int id){代码省略}}interface IFactory{//考题5IDepartment CreateDepartment();//考题6}class SqlServerFactory implements IFactory{public IDepartment CreateDepartment(){return new SqlserverDepartment();}代码省略}class AccessFactory implements IFactory{public IDepartment CreateDepartment(){return new AccessDepartment();}代码省略}
生成器模式(Builder)
1.概念
1.意图
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
2.结构
Builder为创建一个Product对象的各个部件指定抽象接口
ConcreteBuilder实现Builder的接口以构造和装配该产品的各个部件,定义并明确它所创建的表示,提供一个检索产品的接口
Director构造一个使用Builder接口的对象
Product表示被构造的复杂对象
3.适用性
当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时;
当构造过程必须允许被构造的对象有不同的表示时。
2.历年真题
class Pizza{private String parts;public void setParts(String parts){this.parts = parts;}public String toString(){return this.parts;}}abstract class PizzaBuilder{protected Pizza pizza;public Pizza getPizza(){return pizza;}public void createNewPizza(){pizza = new Pizza();}public (1)abstract void buildParts(); //abstract void buildParts()第一题}class HawaiianPizzaBuilder extends PizzaBuilder{public void buildParts(){pizza.setParts("cross+mild+ham&pineapple");}}class SpicyPizzaBulider extends PizzaBuilder{public void buildParts(){pizza.setParts("pan baked+hot+peperoni&salami");}}class Waiter{private PizzaBuilder pizzaBuilder;public void set PizzaBuilder(PizzaBuilderpizzaBuilder){//设置构建器(2)this.pizzaBuilder = pizzaBuilder;}public Pizza getPizza(){return pizzaBuilder.getPizza();}public void construct(){//构建pizzaBuilder.createNewPizza();(3)pizzaBuilder.buildParts();}}class FastFoodOrdering{public static void main(String[] ages){Waiter waiter = new Waiter();PizzaBuilder hawaiian_pizzabuilder = new HawaiianPizzaBuilder();(4)waiter.setPizzaBuilder(hawaiian_pizzabuilder);(5)waiter.comstruct();System.out.println("pizza:" + waiter.getPizza());}}//输出结果//Pizza:cross+mild+ham&pineapple
import java.util.*;class Product {private String part A;private String part B;public Product__(6)__{}public void setPartA(String s){ partA=s;}public void setPartB(String s){ partB=s;}}interface Builder{public (1);public void buildPartB__(7)__;public (2);}class ConcreteBuilder1: implements Builder{private Product product;public ConcreteBuilder1__(8)__{product=new Product__(9)__; }public void buildPartA__(10)__{ (3)("Component A");}public void buildPartB__(11)__{ (4)("Component B");}public Product getResult__(12)__{ return product;}}class ConcreteBuilder2 implements Builder{∥代码省略}class Director {private Builder builder;public Director(Builder builder){this.builder=builder;}public void construct__(13)__{(5)∥代码省略}}class Test{public static void main(String[]args){Director director1=new Director(new ConcreteBuilder1__(14)__);director1.construct__(15)__;}}
原型模式
1、概念
1.意图:用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象
2.结构:Prototype声明一个复制自身的接口;
ConCretePrototype实现一个复制自身的操作
Client让一个原型复制自身从而创建一个新的对象
3.适用性:当一个系统应该独立于它的产品创建、构成和表示时;
当要实例化的类时再运行时刻指定时
为避免创建一个与产品类层次平行的工厂类层次时
当一个类的实例只能有几个不同状态组合的一种时。
向客户隐藏制造新实例的复杂性
在某些情况下,复制对象比创建新的对象更有效
缺点:有时对象的复制相当复杂
2、历年真题
class WorkExperience implementsCloseable{//工作经历 //implements第一题private string workDate;private string company;publicObject Clone(){WorkExperience obj = new WorkExperience();///第二题obj.workDate = this.workDate;obj.company = this.company;return(obj);}}class Resume implements Closeable{//简历//implements 第三题private string name;private string sex;private string age;private WorkExperience work;public Resume(string name){this name=name;work = new SetWorkExperience()}private Resume(WorkExperience work){this work = (WorkExperience)work.Clone();//(WorkExperience)work.Clone();第四题}public void SetPersonallInfo(string sex, String age){代码省略}public void SetWorkExperience(string sex, String age){代码省略}public Object Clone(){Resume obj = new Resume(this.work);//new Resume(this.work);第五题return(obj);}}classWorkResume{public static void main(String[] arg){Resumea =new Resume("");a.SetPersonallnfo("男","29");a.SetWorkExperience("1998~2000","XXX公司");}Resume b = (Resume)a.Clone(); //(Resume)a.Clone(); 第六题b.SetWorkExperience("2001~2006","YYY公司");}
工厂方法(Factory method)
单例模式(Singleton)
结构型设计模式
适配器模式
1.概念
1.意图:将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容的那些类可以一起工作
2.结构:Target定义Client使用的与特定领域相关的接口
Client与符合Target接口的对象协同
Adaptee定义一个已经存在的接口,这个接口需要适配
Adapter对Adaptee的接口与Target接口进行适配
3.适用性:已经存在类,而它的接口不符合要求
想创建一个可以服用的类,该类可以与其他不想关的类或者不可预见的类协同工作
2.历年真题
import java.utils.*;class Address{public void street(){//实现代码省略}public void zip(){//实现代码省略}public void city(){//实现代码省略}//其他成员省略}class DutchAddress{public void straat(){//实现代码省略}public void postcode(){//实现代码省略}public void plaats(){//代码省略}}class DutchAddressAdpter extends DutchAddress{private Address address;//Address address; 第一题public DutchAddressAdapter(Address addr){address = addr;}public void straat(){address.street();}public void postcode(){address.zip();}public void plaats(){address.city();}//省略其他代码}class Test{public static void main(String[] args){Address addr = new Address();DutchAddress addrAdapter = new DutchAddress(addr);testDutch(addrAdapter);}static void testDutch(DutchAddress addr){addr.straat();addr.postcode();addr.plaats();}}
组合模式(Composite)
1.概念
1.意图:将对象组合成树型结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。
2.结构:Component为组合中的对象声明接口留在适当情况下实现所有类共有接口的默认行为;声明一个接口用于访问和管理Component的子组件;
leaf在组合中表示叶结点对象,叶结点没有子节点;在组合定义图元对象的行为。
composite定义有子组件的那些组件的行为;存储子组件;在Component接口中实现与子组件有关的操作;
Client通过Component接口操纵组合组件的对象
3.适用性:想表示对象的部分-整体层次结构
希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
2.历年真题
import java.util.ArryayList;import java.util.List;(1)abstract class AbstarctFile{protected String name;public void printName(){System.out.println(name);}public abstract boolean addChild(AbstractFile file);public abstract boolean removeChild(AbstractFile file);public abstract List getChildren();}class FIle extends AbstractFile{public File(String name){this.name = name;}public boolean addChild(AbstractFile file){return false;}public boolean removeChild(AbstractFile file){return false;}public List getChildren {return (2)null;}}class Folder extends AbstractFile{private List childList;public Folder(String name){this.name = name;this.childList = new ArrayList();}public boolean removeChild(AbstractFile file){return childList.remove(file);}public (3)ListgetChildren() {return (4)childList;}}public class Client{public static void main(Stringp[] args){AbstractFile rootFolder = new Folder("c:\\");AbstractFile compositeFolder = new Folder("composite");AbstractFile windowsFolder = new Folder("windows");AbstractFile file = new File("TestComposite.java");rootFolder.addChild(compositeFolder);rootFolder.addChild(windowsFolder);compositeFolder.addChild(file);//打印目录文件树printTree(rootFolder);}private static void printTree(AbstractFile ifile){ifile.printName();Listchildren = ifile.getChildren();if(children == null) return;for (AbstractFile file:children){(5)printTree(file);}}}/**程序运行结果c:\compositeTestComposite.javawindows*/
桥接(Bridge)
1.概念
1意图:将抽象部分与显示现实部分分离,使它们都可以独立地变化
2.结构:桥接模式Abstraction定义抽象类的接口,维护一个指向Implementor类型对象的指针。
RefinedAbstraction 扩充由Abstraction定义的接口
Implementor定义实现类的接口
ConcreteImplementor实现Implementor接口并定义它的具体实现。
适用性:想在多个对象间共享实现
有许多类要生成的类层次结构
对一个抽象的实现部分的修改应对客户不产生影响
不希望在抽象和它实现部分之间有一个固定的绑定关系
类的抽象以及它的实现都应该可以通过生成子类的方法进行扩充
2.历年真题
import java.util.*;class Matrix{//代码省略}abstract class Implementor{public (1)abtract void dopaint(Matrix m);//显示像素矩阵m //第一题abtract void dopaint(Matrix m)}class WinImp extends Implementor{public void doPaint(Matrix m){}//调用Windows系统的绘制函数绘制像素矩阵}class LinuxImp extends Implementor{public void doPaint(Matrix m){}//调用Windows系统的绘制函数绘制像素矩阵}abstract class Image{public void setImp(Implementor imp){this.imp = imp;}public abstract void parseFile(String fileName);protected Implementor imp;}classBMPImage extends Image{//代码省略}class GIFImage extends Image{public void parseFile (String fileName){//此处解析BMP文件并获得一个像素矩阵对象m(2)imp.doPaint(m);//显示像素矩阵m//第二题imp.doPaint(m);}class JPEGImage extends Image{//此处代码省略}class Main{public static void main(String[] args){Image image = (3)new GIFImage();//第三题new GIFImage()Implementor imageImp =(4)new LinuxImp();//第四题 new LinuxImp()(5)image.setImp(imageImp);//第五题image.setImp(imageImp)image.parseFile("demo.gif");}}}
装饰
1.概念
2.历年真题
import java.util.*;(1) class Beverage{//饮料String description "Unknown Berverage";public (2)(){return description;}public (3);}abstract class CondimentDecorator extends Beverage{//配料(4);}class Espresso extends Beverage{//蒸馏咖啡private final int ESPRESSO_PRICE = 25;public Espresso(){description = "Expresso";}public int cost(){return ESPRESSO_PRICE;}}class DarkRoast extends Beverage{private final int DARKROAST_PRICR = 20;public DarkRoast(){description = "DarkRoast";}public int coast(){return DARKROAST_PRICE;}}class Mocha extends COndimentDecorator{private final int MOCHA_PRICE = 10;public Mocha(Beverage beverage){this.beverage = beverage;}public String getDescription(){return beverage.getDescription() + ",Mocha";}public int coast(){return MOCHA_PRICE + beverage.cost();}}class Whip extends CondimentDecorator{//奶泡private fianl int WHIP_PRICE = 8;public Whip (Beverage beverage){this.beverage = beverage;}public String getDescription(){return beverage.getDescription() + ",Whip";}public int cost(){return WHIP_PRICE + beverage.cost();}}public class Coffee{public static void main(String args[]){Beverage beverage - new DarkRoast();beverage = new Mocha(5);beverage = new Whip(6);System.out.println(beverage.getDescription() + "Y" + beverage.cost())}}//运行结果DarkRoast, Mocha, Whip ¥38
外观
享元
import java.util.*:enum PieceColor {BLACK,WHITE}//棋子颜色class PiecePos{//棋子位置private intx;private int y:pubic PiecePos(int a,int b){x=a;y=b;}public int getX0{retun x;}public int getYO{return y;}}abstract class Piece{//棋子定义protected PieceColor m_color;//颜色protected Piecemopos m_pos;//位置public Piece(PieceColor,color PiecePospos){m color=color;{:sod=sod u(1);}class BlackPiece extends Piece{public BlackPiece(PieceColorcolor,PiecePos pos){super(color,pos);}public void drawO{System out println("draw a blackpiece");}}class WhitePiece extends Piece{public WhitePiece(PieceColorcolor,PiecePos pos){super(color,pos):}public void draw0{System.out.println("draw a whitepiece");}{class PieceBoard{//棋盘上已有的棋子private static finalArrayListm_arrayPiece=new ArrayListprivate String m_blackName;//黑方名称private String m_whiteName;//白方名称public PieceBoard(String black,Stringwhite){m_blackName=black;m_whiteName=white;}//一步棋,在棋盘上放一颗棋子public void SetePiece(PieceColorcolor,PiecePos pos){(3)piece=null;if(color==PieceColor.BLACK)(//放黑子piece=new BlackPiece(color,pos);//获取一颗黑子System.out.println(m_blackName+"在位置("+pos.getX0)+","+pos.getYO+")");(4):{else{//放白子piece=new WhitePiece(color,pos);//获取一颗白子System.out.println(m whiteName+"在位置("+pos.getX0)+","+pos.getYO+")");(5):}m_arrayPiece.add(piece);}}信管网参考答案:(1)public abstract void draw( )(2)Piece(3)Piece(4)piece.draw( )(5)piece.draw( )
行为设计模式
责任链
命令
1.概念
2.历年真题
【Java代码】class Light{public Light0{}public Light(String name){/*代码省略*/}public void on(/*代码省略*/} //开灯public void off() {/*代码省略*/} //关灯//其余代码省略)(1) {public void execute();}class LightOnCommand implements Command{//开灯命令Light light;public LightOnCommand(Light light){this. light=light;}public void execute0{ (2) ;}}class LightOffCommand implements Command{//关灯命令Light light;public LightOffCommand(Light light){this. light=light;}public void execute( ){ (3)_;}}class RemoteControl{//遥控器Command[]onCommands=new Command[7];Command[]offCommands=new Command[7];public RemoteControlO{/*代码省略*/}public void setCommand(int slot, Command onCommand, Command offCommand){ (4) =onCommand;(5) =offCommand;17public void onButtonWasPushed(int slot){(6)}public void offlButtonWasPushed(int slot){(7);}}class RemoteLoader{public static void main(String[]args){RemoteControl remoteControl=new RemoteControl0;Light livingRoomLight=new Light("Living Room");Light kitchenLight=new Light("kitchen");LightOnCommandlivingRoomLightOn=new LightOnCommand(livingRoomLight);LightOffCommandlivingRoomLightOff=new LightOffCommand(livingRoomLight);LightOnCommandkitchenLightOn=new LightOnCommand(kitchenLight);LightOffCommandkitchenLightOff=new LightOffCommand(kitchenLight);remoteControl.setCommand(0,livingRoomLightOn,livingRoomLightOff);remoteControl.setCommand(1,kitchenLightOn,kitchenLightOff);remoteControl.onButtonWasPushed(0);remoteControl.offButtonWasPushed(0);remoteControl.onButtonWasPushed(1);remoteControl.offButtonWasPushed(1);}
解释器
迭代器
中介者
备忘录
观察者
import java.util.*;interface Observer {public void update(float temp, float humidity, float cleanness);}interface Subject {public void registerObserver(Observer o); //注册对主题感兴趣的观察者public void removeObserver(Observer o); //删除观察者public void notifyObservers(); //当主题发生变化时通知观察者}class EnvironmentData implements (1) {private ArrayList observers;private float temperature, humidity, cleanness;public EnvironmentData() { observers = new ArrayList(); }public void registerObserver(Observer o) { observers.add(o); }public void removeObserver(Observer o) { /* 代码省略 */ }public void notifyObservers() {for (int i = 0; i < observers.size(); i++) {Observer observer = (Observer)observers.get(i); (2) ;}}public void measurementsChanged() {(3) ; }public void setMeasurements(float temperature, float humidity, float cleanness) {this.temperature = temperature;this.humidity = humidity;this.cleanness = cleanness; (4);}}class CurrentConditionsDisplay implements(5){private float temperature;private float humidity;private float cleanness;private Subject envData;public CurrentConditionsDisplay(Subject envData) {this.envData = envData; (6) ;}public void update(float temperature, float humidity, float cleanness) {this.temperature = temperature;this.humidity = humidity;this.cleanness = cleanness;display();}public void display() {/* 代码省略 */ }}class EnvironmentMonitor{public static void main(String[] args) {EnvironmentData envData = new EnvironmentData();CurrentConditionsDisplay currentDisplay = new CnrrentConditionsDisplay(envData);envData.setMeasurements(80, 65, 30.4f);}}
状态
1、概念
2、历年真题
import java.util.*;interface State{public void insertQuarter();public void ejectQuarter();public void turnCrank();public void dispense();}class TissueMachine{(1) State soldOutState, noQuarterState, hasQuarterState, soldState, state;//第一题State state = soldOutState; int count = 0; //纸巾数 public TissueMachine(int numbers){//实现代码省略} public State getHasQuarterState(){ return hasQuarterState; } public State getNoQuarterState(){ return NoQuarterState; } public State getSoldState(){ return soldState; } public State getSoldOutState(){ return soldOutState; }public int getCount(){return count;}//其余代码省略}class NoQuarterState implements State{TissueMachine tissueMachine;public void insertQuarter(){tissueMachine.setState((2)tissueMachine.getHasQuarterStat());}//构造方法及其余代码省略}class HasQuarterState implements State{TissueMachine tissueMachine;public void ejectQuarter(){tissueMachine.setState(3)tissueMachine.getNoQuartState();}//构造方法以及其余代码省略}class SoldState implements State{TissueMachine tissueMachine;public void dispens(){if(tissueMachine.getCount()>0){tissueMachine.setState(4)tissueMachine.getNoQuartState();}else{tissueMachine.setState(5)tissueMachine.getSoldOutState();}}}
策略
Import java. Util.*;Enum TYPE{NORMAL,CASH_DISCOUNT,CASH_RETURN};Interface CashSuper{Public (1) ;}Class CashNormal implements CashSuper{ //正常收费子类Public double accptCash(double money){Return money;}}Class CashDiscount implements CashSuper {Private double moneyDiscount; //折扣率Public CashDiscount(double moneyDiscount) {This moneyDiscount= moneyDiscount;}Public double acceptCash(double money) {Return money*moneyDiscount;}}Class CashReturn implements CashSuper { //满额返利Private double moneyCondition;Private double moneyReturn;Public CashReturn(double moneyCondition, double moneyReturn) {This.moneyCondition=moneyCondition; //满额数额This.moneyReturn=moneyReturn; //返利数额Public double acceptCash(double money){Double result=money;If(money>=moneyCondition )Result=money-Math. Floor(money/moneyCondition) *moneyReturn return result;}}Class CashContext_{Private CashSuper cs;Private TYPE t;Public CashContext(TYPE t) {Switch(t){Case NORMAL: //正常收费(2) ;Break;Case CASH_DISCOUNT:(3);break;Case CASH_RETURN:(4);break;}}public double getResult(double money){(5)}//此处略去main()函数}
模板方法
访问者
import java.util.*;interface LibraryVisitor{ (1)(2)void printSum();}Class LibrarySumPrintVisitor implements LibraryVisitor{//打印总页数private int sum=0;Public void visit( Book p_book){Sum= sum+p_book.getNumberOfPages( );Public void visit( Article p_article){Sum= sum+p_article.getNumberOfPages0;Public void printSum(){System. Out. Println(“SUM=”+sum);))Interface LibraryItemInterface {(3) ;)Class Article implements LibraryItemInterface{Private String m_title;//价仑文名。Private String m_author;//仑文作者Private int m_start_page;Private int m_end_page;Public Article( String p_author, String p_title, int p_start_page, int p_end_page){M_title=p_title;M_author=p_author;M_end_page=p_end_page;)Public int getNumbel0fPages(){Rctum m end_page-m_start_page;)Public void acccpt(LibraryVisitor Visitor){(4) :))Class Book implements LibraryItemInterface{Private String m_title;//书名Private String m_author;//书作者Private int m_pages;//页教Public Book( String p_author, String p_title, int p_pages){M_title=p_title;M_author=p_author;M_pages=p_pages;}public int getNumberOfPages(){return m_pages;}public void accpet (LibraryVisitor visitor){ (5);}}