黑马程序员------装饰设计模式和单例设计模式

来源:互联网 发布:软件维保合同范本 编辑:程序博客网 时间:2024/06/06 08:25

android培训、java培训、

/*装饰设计模式就是基于已有的类,对其进行功能的增强。实现方法是将已有类的对象作为参数传入装饰类的构造函数,在装饰类中队已有类的方法进行功能增强。例如:*/class Person{public void gongzuo(){System.out.println("开始工作。");}}//对Person类进行装饰class NewPerson{private Person p;NewPerson(Person p){this.p = p;}public void newGongzuo(){System.out.println("打开电脑");p.gongzuo();System.out.println("关闭电脑");}}//继承也可以达到同样的效果,但是为什么不适用继承呢?/*举一个改装车辆的例子:车奔驰跑车房车宝马跑车房车如果要将一辆奔驰车改成跑车,适用继承,则要将跑车定义为其子类,要改成房车则又要衍生一个子类。对宝马车进行改造又要重复同样的过程,如果再有奥迪车等等车,则还需重复此步骤,所以显得结构比较臃肿。如果用装饰设计模式,则过程是:车奔驰宝马奥迪。。。改成房车(车)改成跑车(车)只需在改成跑车类中,对传入的车进行跑车特性的增加即可。*///实现如下:abstrect class Car{public abstrect void run();}class Benchi extends Car{public void run(){System.out.println("奔驰run");}}class Baoma extends Car{public void run(){System.out.println("宝马run");}}class Gaichengfanche extends Car{private Car c;Gaichengfanche(Car c){this.c = c;}public void gaiZhuang(){System.out.println("加装房车组件");}public void newCarRun(Car c){this.gaiZhuang();c.run();}}Class Gaichengpaoche extends Car{private Car c;Gaichengpaoche (Car c){this.c = c;}public void gaiZhuang(){System.out.println("加装跑车组件");}public void newCarRun(Car c){this.gaiZhuang();c.run();}}/*单例设计模式,单例设计模式是为了保证内存中,某一个类只有一个对象存在。主要有两种实现方式。饿汉式和懒汉是,程序中建议使用饿汉式,因为安全。懒汉是如果在多线程中使用需涉及线程同步问题。*///饿汉式class Singleton{//私有化构造方法,使外界不能建立本类对象。private Singleton(){}//在内部提供一个静态私有的本类对象。private static Singleton instence = new Singleton();//提供外部访问方法。public Singleton getInstence(){return instence;}}//懒汉式class Singleton{private Singleton(){}private static Singleton instence = null;public Singleton getInstence(){//先判断instence是否为空,如果为空则直接返回。if(instence==null){synchornized(Sinleton.class){if(instence==null)instence = new Singleton();}}return instence;}}