装饰器模式就是在原有的基础之上动态添加新的功能,这种添加模式不同于继承,它主要是在对象层面实现功能拓展,而不同于继承类的层面,装饰器模式比继承要更加的灵活。
例子:
原版功能的机器人可以进行对话唱歌这两项功能,现在要在对话唱歌这两个功能之上添加新的功能,但是因继承的耦合度过高,所以采用装饰器模式,从而降低对代码 的修改。
package 装饰器模式;
public class DecoratorPattern { //装饰器模式
}
interface Robot{ //接口
void doSomething();
}
class FirstRobot implements Robot{//第一代机器人
@Override
public void doSomething() {
System.out.println("对话"); //第一代机器人所能干的事情;
System.out.println("唱歌");
}
}
class RobotDecorator implements Robot{//机器人构造器实现机器人接口。
private Robot robot; //最重要的一段代码
public RobotDecorator(Robot robot) {//构造器传入新的代码机器人。
this.robot=robot;
}
@Override
public void doSomething() {
robot.doSomething();
}
public void doMoreThing() { //设置新的功能
robot.doSomething();
System.out.println("洗碗");
}
public static void main(String[] args) {
FirstRobot fr=new FirstRobot();
RobotDecorator rd=new RobotDecorator(fr);
rd.doMoreThing();
}
}
单例模式:
确保一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,实例化在类内实现。
例子:
public class SinglentonPattern{ //单例模式
public static void main(String[] args){
}
}
class Singleton{
private static Singleton singleton;//唯一一个实例,静态变量,目前singleton是空
private Singleton(){}//单例模式构造器必须私有
public static Singleton getInstance(){
return null;
}
}
实例化时机:饿汉式、懒汉式
饿汉模式,在定义成员变量时候变实例化:
public class SinglentonPattern{ //单例模式
public static void main(String[] args){
}
}
class Singleton{
private static Singleton singleton=new Singleton;类加载的时候立刻进行实例化。
private Singleton(){}//单例模式构造器必须私有
public static Singleton getInstance(){
return null;
}
}
懒汉模式:
public class SinglentonPattern{ //单例模式
public static void main(String[] args){
}
}
class Singleton{
private static Singleton singleton;//唯一一个实例,静态变量,目前singleton是空
private Singleton(){}//单例模式构造器必须私有
public static synchronized Singleton getInstance(){ //synchronized
if(singleton==null)//如果singleton是空的时候,那么进行实例化。
singleton=new Singleton;
return null;
}
}



