单例设计模式:
希望对象只创建一个实例,并且提供一个全局的访问点。
public class SingleDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1);
Singleton single = Singleton.getInstance();
System.out.println(single + "----1");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(2);
Singleton single = Singleton.getInstance();
System.out.println(single + "----2");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread2.start();
}
}
class Singleton {
private Singleton(){}
private static Singleton single = null;
public static synchronized Singleton getInstance() {
if (single == null) {
single = new Singleton();
}
return single;
}
}
/*不加锁
* 先执行的thread2这个线程,当程序执行到single = new Singleton();这行代码时,
* CPU迅速切换到thread1这个线程,判断为空,再创建一个对象
*
package1.Singleton@3020ad----1
package1.Singleton@1b15692----1
package1.Singleton@1b15692----1
package1.Singleton@1b15692----1
package1.Singleton@1b15692----2
package1.Singleton@1b15692----1
package1.Singleton@1b15692----2
package1.Singleton@1b15692----1
package1.Singleton@1b15692----2
...*/
装饰设计模式:
当想要对已有的对象进行功能增强时,
可以定义一个类,将已有对象传入,基于已有的功能,并提供加强功能
装饰类通常会通过构造方法接受被装饰的对象
并基于被装饰的对象的功能,提供更详细的功能。
class Person {
public void eat() {
System.out.println("吃饭");
}
}
class DecoratorPerson {
private Person p;
DecoratorPerson(Person p) {//构造方法传递
this.p = p;
}
public void decotatorEat() {//提供了比eat()方法额外的功能
System.out.println("开胃酒");
p.eat();
System.out.println("甜点");
System.out.println("吸根烟");
}
}
class Test {
public static void main(String[] args) {
Person p = new Person();
DecoratorPerson sp = new DecoratorPerson(p);
sp.decotatorEat();
}
}
工厂模式;
提供创建对象的接口. 为系统结构提供了非常灵活强大的动态扩展机制,只要我们更换一下具体的工厂方法,系统其他地方无需一点变换,就有可能将系统功能进行改头换面的变化。
public class Test {
public static void main(String[] args) {
Product washer=Factory.create(1);//通过工厂中的方法指定要创建的对象
Product icebox=Factory.create(2);//针对接口编程
}
}
class Factory{
public static Product create(int x){
if(x==1)
return new Washer();
if(x==2)
return new Icebox();
return null;
}
}
interface Product{
}
class Washer implements Product {
Washer() {
System.out.println("洗衣机被制造了");
}
}
class Icebox implements Product {
public Icebox() {
System.out.println("冰箱被制造了");
}
}