基本的几个设计模式
来源:互联网 发布:骁龙835支持5g网络吗 编辑:程序博客网 时间:2024/04/26 01:24
- 简单工厂模式
- 单例模式
- 建造者模式(Builder)
- 原型模式(prototype)—克隆
- 中介者模式(Mediator)
- 代理模式
- 观察者模式(Observe)
- 策略模式(strategy)
- 状态模式
- 享元模式(Flyweight)
- 装饰器模式
简单工厂模式
public interface Car(){ public void run();}public class Audi implements Car(){ @Override public void run(){ System.out.println("奥迪在跑!"); }}public class Benz implements Car{ @Override public void run(){ System.out.println("奔驰在跑!"); }}public class CarFactory{ public static Car createCar(String type){ Car c=null; if("奥迪".equals(type)){ c=new Audi(); }else if("奔驰".equals(type)){ c=new Benz(); } return c; }}public class Client{ public static void main(String []){ Car c1 =CarFactory.createCar("奥迪"); Car ce =CarFactory.createCar("奔驰"); c1.run(); c2.run(); }}
思考问题:
1.公司里,办公用品的领取过程?
2.sun公司设计java时,为解决操作系统之间的差异采用什么手段?
3.Spring的ioc容器的作用,跟我们工厂模式的关系?
(BeanFactory,bean class=”” ..可以通过反射来new 对象。可以把每个new 对象放在map里提高效率。)Factory一般用单例来做。
本质:将实现类、创建类对象统一管理控制,从而将客户端程序跟我们的实现类解耦。
单例模式
保证一个类只有一个实现对象。(如serlvet)
思考如下场景:
1.项目中,读取配置文件的类,一般也只有一个对象。有无必要每次使用配置文件数据,每次new一个对象去读取?
懒汉式单例模式代码:
public class singletonDemo{ private static SingletonDemo s; private SingletonDemo(){}; //私有化构造器 public static synchronized SingletonDemo getInstance(){ if(s==null){ s=new SingletonDemo(); } return s; }}public class Client( public static void main(String[] args){ SingletonDemo s=singletonDemo.getInstance(); SingletonDemo s2=singletongDemo.getInstance(); System.out.println(s==s2);//结果为true
饿汉式单例模式代码:
public class SingletonDemo2{ private statice SingletonDemo2 s=new SingletonDemo2();//第一次加载就被创建,不会发生线程冲突 private SingletonDemo2(){} //私有化构造器 public static singletonDemo2 getInstance(){ return s; } } public class Client{ public statice void main(String [] args){ SingletonDemo s=SingletonDemo.getInstance(); SingletonDemo s1=SingletonDemo.getInstance(); System.out.prinln(s==s2);//结果为true } }
比如sessionfactory servlet都是单例
建造者模式(Builder)
场景:
1.我们要建造一个复杂的产品,比如:神舟飞船。这个复杂的产品的创建。有这样一个问题需要处理:
装配这些子组建是不是有个步骤问题。
2.实际开发中,我们所需要的对象构建时,也非常复杂,有很多步骤需要处理。
public class Airship{ private String orbitalModule;//轨道舱 private String engine;//发动机 private String escapeTower;//逃逸塔 public String getOrbitalModule(){ return orbitalModule; } public void setOrbitalModule(String orbitalModule){ this.orbitalModule=orbitalModule; } public String getEngine(){ return engine; } public void setEngine(String engine){ this.engine=engine; } public String getEscaperTower(){ return escapeTower; } public void setEscapeTower(StringescapeTower){ this.escapeTower=escapeTower; } } public interface AirshipBuilder{ public void builderEngine(); public void builderOrbitalModule(); public void buildderEscapeTower(); } public class ConcreteAirshipBuilder implements AirshipBuilder{ private Airship airship=new Airship(); @Override public void buildderEscapeTower(){ System.out.println("建筑逃逸塔,over"); airship.setEscapeTower("莫莫牌逃逸塔!"); } @Override public void builderEngine(){ System.out.println("建造发动机,over"); airship.setEngine("莫莫牌火箭发动机"); } @Override public void builderOrbitalModule(){ System.out.println("建造轨道舱,over!"); airship.setOrbitalModule("莫莫牌轨道舱"); } public Airship getAirship(){ return ariship; } public void setAirship(Airship airship){ this.airship=airship; } } public class Director{//装配顺序指导 public void creteAirship(AirshipBuilder builder){ builder.builderEngine(); builder.builderOrbitalModule(); builder.builderEscaperTower(); } } public class Client{ public statice void main(String [] args){ ConcreteAirshipBuilder builder=new ConcreteAirshipBuilder(); Diretor director =new Director(); director.createAirship(builder); Airship shenzhou1=builder.getAirship(); System.out.println(shenzhou1.getEngine()); } }
建造者模式反应了构建类的细节,相当于流水线、装配车间。(StringBuidler、xml解析)
原型模式(prototype)—克隆
场景:
1.思考一下:克隆技术是怎么样的过程?
2.javascript语言中,继承怎么实现?那里面也有prototype.
就是java种的克隆技术,以某个对象为原型,复制出新的对象。他的优势有:效率高(直接克隆,并且避免了重新执行构造过程的步骤)、”接口造接口”。
克隆类似于new ,但是不同于new .new 创建新的对象属性采用的是默认值。克隆出的对象属性值和原型对象相同。并且克隆出的新对象改变不会影响原型对象。
public class Sheep implements Cloneable{ private String name; @Override protected Object clone(){ object obj=null; try{ obj=super.clone();//直接调用父类的clone方法即可! }catch(CloneNotSupportedException e){ e.printStackTrace(); } return obj; } public String getSname{ return sname; } public Sheep(){ } } public class Client{ public static void main(String [] args){ Sheep s1=new Sheep("多利"); Sheep s2=(Sheep)s1.clone(); System.out.println(s1+"--"+s1.getSname()); System.out.println(s2+"--"+s2.getSname()); }
可能有深复制、浅复制;
浅克隆:
深克隆:
1.spring管理structs2总,action是否使用了prototype模式?
中介者模式(Mediator)
场景:
1.假如公司没有总经理。下面三个部门:财务部、市场部、研发部。财务部要发工资,会非常复杂。
public interface Department{ void action();//做本部门的事情 void advice();//像总经理发出申请 } public class Development implements Department{ private President p;//总经理 @Override public void action(){ System.out.println("技术部在开发项目!"); } @Override public void advice(){ System.out.println("向总经理报告开发进度,需求资金支持!"); } public Development(President p){ super(); this.p=p; p.reqesiter(this,2); } public Development() {} } public class Finacial implements Department{ private President p;//总经理 @Override public void action(){ System.out.println("财务部在数钱!"); } @Override public void advice(){ System.out.println("发工资了!"); } public Development(President p){ super(); this.p=p; p.reqesiter(this,3); } public Finacial() {} } public class Market implements Department{ private President p;//总经理 @Override public void action(){ System.out.println("市场部在接项目!"); } @Override public void advice(){ System.out.println("市场部报告项目承接进度,需要资金支持!"); p.receive(3); } public Development(President p){ super(); this.p=p; p.reqesiter(this,1); } public Market() {} } public interface Mediator{ void regesiter(Department department,int type); void command(int type); void receive(int type); } public class President implements Mediator{ Market m; Developmet d; Finacial f; @Override public void command(int type){ switch(type){ case 1: m.action(); break; case 2: d.action(); break; case 3: f.action(); break; } } @Override public void regesiter(Department department,int type){ switch(type){ case 1: m=(Market)department; break; case 2: d=(Development) dapartment; break; case 3: f=(Financial)department; break; } } @Override public void receive(int type){ System.out.println("受到部门消息!"); command(type); } } public class Client{ public static void main(String [] args){ President p=new President(); Market m=new Market(p); Development d=new Development(p); Finacial f=new Finacial(p); m.advice(); } }
类图:
初级写游戏时,窗口类是中介者。
代理模式
1.数据库连接池的动态代理的实现。2.struct2 Invocation代理类返回一个aciotn3.sprint AOP动态代理是aop重要的手段。思考下列问题:1.结合动态代理模式,研究structs2中的控制流程Invocation 对象和代理原理。2.hibernate中的懒加载时如何使用代理模式的?3.aop的实现(拦截器都是aop的实现).(时序图)
观察者模式(Observe)
场景:
1.聊天室程序的创建。
2.主题的订阅,当有新内容,则发给所有人。
3.大家一起玩cs游戏,服务器需要和、将每个人的方位变化发给所有的客户。
public interface Observer{ void update(Subject subject); } public class ObserverA implements Observer{ private int mystate;//需要让观察者的状态和目标对象状态保持一致! @Override public void update(Subject subject){ mystate=((ConcreteSubject)subject).getState(); } public int getMystate(){ return mystate; } public void setMystate(int mystate){ this.mystate=mystate; } } public class Subject{private List<Observer> list=new ArrayList<Observer>(); //注册观察者对象 public void attach(Observer obs){ list.add(obs); } //删除观察者 public void delete(Observer obs){ list.remove(obs); } //通知所有的观察者更新目标对象的状态 protected void notifyAllObservers(){ for(int i=0;i<list.size();i++){ list.get(i).update(this); } } public class ConcreteSubject extends Subject{ private int state; public int getState(){ return state; } public void setState(int state){ this.state=state; this.notifyAllObervers(); } } public class Client{ public static void main(String [] args){ ConcreteSubject subject=new ConcreteSubject(); //创建观察者 ObserverA obs1=new ObserverA(); ObserverA obs2=new ObserverA(); //将上面两个观察者添加到subject的观察队伍中 subject.attach(obs1); subject.attach(obs2); //改变subject的状态 subject.setState(1); //我们看看观察者obs2的状态是不是跟subject状态同步 System.out.println(obs2.getMystate()); }
类图:
1.awt和swing中,事件处理是不是观察者模式?
2.自学并说明,java.util.Observale的作为,并使用这个类来实现观察者模式。
策略模式(strategy)
场景:
1.报价策略:
a)普通客户小批量报价
b)普通客户大批量报价
c)老客户小批量报价
d)老客户大批量报价
设计模式中有”开闭原则”,对扩展开放,对修改关闭。
public interface Strategy{ public double getprice(double standardprice); } public class NewCustomerfewStrategy implements Strategy{ @override public double getPrice(double standardPrice){ return standardPrice; } } public class NewCustomerManyStrategy implements Strategy{ @Override public double getPrice(double standardPrice){ return standardPrice*0.9; } } public class OldCustomerfewStrategy implements Strategy{ @Override public double getPrice(double standardPrice){ return standardPrice*0.85; } } public class OldCustomerfewStrategy implements Strategy{ @Override public double getPrice(double standardPrice){ return standardPrice*0.8; } } //负责与策略类交互 public class Context{ private Strategy strategy; public Context(Strategy strategy){ super(); this.strategy=strategy; } public void printPrice(double s) { //打印出报价 System.out.println("您的报价:"+strategy.getPrice(s)); } } public class Client{ public static void main(String[] args){ Strategy s1=new OldCustomerfewStrategy(); Context cxt=new Context(s1); cxt.printPrice(220); } }
某一个流程可以多种算法实现,可以用策略模式。
状态模式
场景:
1.某个对象状态不同,对应处理方式不一样。
2.公文流转过程。状态有提交、审核、审核未通过、审核未通过、归档等状态,对应处理也不同。
网购过程中,下订单,付款。
public interface State{ void handle(String param); } public class BillState implements State{ @Override public void handle(String param){ System.out.println("下订单:"+param); } } public class PayState implements State{ @Override public void handle(String param){ System.out.println("付账:"+param); } } public class Context{ private State state; public void changeState(State s){ state=s; state.handle("202"); } public class Client{ public static void main(String [] args){ Context ctx=new Context(); ctx.changeState(new BillState()); ctx.changeStete(new PayState()); } }
主要在业务逻辑层工作流用到了设计模式。
享元模式(Flyweight)
场景:
1.一般用于缓存的设计。
对于一些对象的属性值变动不平凡,可以放内存中,设计享元
public interface Font{ public abstract void SetFont(String color,int size); public abstract void GetFont(); } public class ConcreteFont implements Font{ private String color; private int size; private String str; public ConcreteFont(String s){ str=s; } public void SetFont(String _color,int _size){ color=_color; size=_size; } public void GetFont(){ System.out.println("String :"+ str+"---color---size is:"+size); } } public class FontFactory{ private Hashtable charHashTable=new Hashtable(); public Font GetFlyweight(String s){ if(charHashTable.get(s)!=null){ return (Font)charHashTable.get(s); }else{ Font tmp=new ConcreteFont(s); charHashTable.put(s,tmp); return tmp; } } public Hashtable GetFactory(){ return charHashTable; } } public class Test{ public static void main(String [] args){ FontFactory myFontFactory=new FontFactory();//一般将享元工厂设成单例 Font f1=myFontFactory.GetFlyWeight("aa"); Font f2=myFontFactory.GetFlyWeight("bb"); Font f3=myFontFactory.GetFlyWeight("aa"); System.out.println(f1); System.out.println(f2); System.out.println(f3); } }
1.hibernate缓冲也是
装饰器模式
场景: 1.年底了,要发奖金.年终奖如何计算? a)当月基本奖金 b)当月团队奖金 c)当年个人奖金 d)当年团队奖金 最终拿到手的应该是上面这些计算的总和。
public abstract class Component{ abstract void operation(); } public class ConcreteComponent extends Component{ @override void operation(){ System.out.println("我是被装饰对象的operation方法!"); } } public abstract class Decorator extends Component{ protected Component component; public Decorator(Component component){ this.component=component; } } @Override void operation(){ System.out.println("我在调用被装饰对象的operation方法之前!"); component.operation(); System.out.println("我在调用被装饰对象的operation方法之后!"); } } public class ConcreteDecoratorA extends Decorator{ public ConcreteDecoratorA(Component component){ super(component); } public void operation(){ System.out.println("ConcreteDecoratorA中,可以在调用被装饰方法前做某些处理!"); super.operation(); System.out.println("ConcreteDecoratorA中,可以在调用被装饰方法后做某些处理!"); } } public class Client{ public static void main(String [] args){ Component c=new ConcreteComponent(); Decorator d=new ConcreteDecoratorA(c); d.operation(); } }
inputstream 如:InputStream is=new Fileinputstream("d:/a.txt");InputStream bis=new BufferedReadReader(is);bis.read();structs2中request等对象的封装处理;request(map) 在servlet中为对象,利用装饰器进行了封装。
- 基本的几个设计模式
- 设计模式之几个基本设计原则
- Java中的几个基本设计模式
- 几个基本的设计原则
- 设计模式的几个原则
- 设计模式的几个基本原则
- 几个设计模式的例子
- 常用的几个设计模式
- 设计模式的几个原则
- 基本的设计模式
- 单片机设计的几个基本问题
- 硬件设计的几个基本问题
- iOS的基本设计模式
- 一些基本的设计模式
- 一些基本的设计模式
- 一些基本的设计模式
- iOS的基本设计模式
- iOS的基本设计模式
- python多线程编程(5): 条件变量同步
- 【C#】C#winform 双击/按"F12"键全屏,按"Esc"键退出
- MVC, WEB MVC, SPRING MVC 图解
- 自我学习,监督学习,半监督学习和迁移学习的区别
- [LeetCode]142. Linked List Cycle II
- 基本的几个设计模式
- linux下配置maven运行环境
- spring mvc框架概述
- Maven的安装配置
- ngnix做Https访问设置及依据URL后缀分流访问
- mysql 优化--定位慢查询
- Error:Execution failed for task ':app:mergeDebugResources'. > Error: java.lang.RuntimeException: Som
- 滑动RecyclerView时隐藏部分控件
- iOS 创建语言提示成功后自动消失