设计模式

http://c.biancheng.net/view/1348.html

 

 

package com.spring.inter.development.testcontroller;

import com.inrdev.Entity.User;

import java.util.concurrent.atomic.AtomicInteger;
public class JavaTestController {
public static void main(String[] args) throws InterruptedException {

/**
* 单例模式的测试
*/
/*Thread[] threads = new Thread[2];
//int count = 0;
for (int ii = 0; ii < threads.length; ii++) {
// count++;
threads[ii] = new Thread( () -> {
AtomicInteger count = new AtomicInteger(0);
Singleton instance = Singleton.getINSTANCE();
System.out.println(instance+"...."+count.incrementAndGet());
});
//System.out.println(count++);
}
for (Thread thread : threads) thread.start();
for (Thread thread : threads) thread.join();
System.out.println(threads[0] +"......"+ threads[1]);*/
/**
* 原型模式测试
*/
Prototype prototype = new Prototype();
Prototype clone = (Prototype)prototype.clone();
System.out.println(prototype == clone);
}
}

/**
* 单例模式
*/
class Singleton{
private static volatile Singleton INSTANCE = null;

private Singleton(){}

public static synchronized Singleton getINSTANCE() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}else{
System.out.println("该单例已经创建");
}
return INSTANCE;
}
}

/**
* 原型模式:prototype
*/
class Prototype implements Cloneable{
Prototype(){
System.out.println("具体原型创建成功!");
}
public Object clone (){
System.out.println("具体原型复制成功!");
Prototype clone = null;
try {
clone = (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
/**
* 工厂模式:
* 特点:定义一个创建产品对象的工厂接口,将产品对象的实际创建工作推迟到具体的子类工厂中
* 结构:
* 1.抽象工厂
* 2.具体工厂
* 3.抽象产品
* 4.具体产品
*/
//抽象产品
interface Product{
public void show();
}
//具体产品
class CreateProduct implements Product {

@Override
public void show() {
System.out.println("产品1生产出来了!");
}
}
//抽象工厂
interface AbstractFactory{
public Product newProduct();
}
//具体实现工厂
class CreateFactory implements AbstractFactory{

@Override
public Product newProduct() {
System.out.println("生产出来了");
return new CreateProduct();
}
}
posted @ 2020-06-12 14:08  孤独的根号er  阅读(162)  评论(0编辑  收藏  举报