[TOC]
## 單例模式
~~~
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
~~~
## 工廠模式
~~~
public interface IProduct{
public void use();
}
public class ProductA implements IProduct {
public void use(){
System.out.println("use A");
}
}
public class ProductB implements IProduct {
public void use(){
System.out.println("use B");
}
~~~
### 普通工廠模式
~~~
public class MyFactory{
public IProduct create(String type){
if("A".equals(type)){
return new ProductA();
}else if("B".equals(type)){
return new ProductB();
}
}
}
~~~
### 多個工廠方法模式
~~~
public class MyFactory{
public IProduct createA(){
return new ProductA();
}
public IProduct createB(){
return new ProductB();
}
}
~~~
### 抽象工廠模式
~~~
public interface IFactory{
public IProduct create();
}
public class FactoryA implements IFactory{
public IProduct create(){
return new ProductA();
}
}
public class FactoryB implements IFactory{
public IProduct create(){
return new ProductB();
}
}
public void test(){
IFactory factoryA = new FactoryA();
IProduct productA = factoryA.create();
~~~
## 生產者消費者模型
生產者生產數據到緩沖區中,消費者從緩沖區中取數據。
如果緩沖區已經滿了,則生產者線程阻塞;
如果緩沖區為空,那么消費者線程阻塞。
~~~
public interface ITaskQueue{
public void add();
public int remove();
}
public class Consumer extends Thread{
ITaskQueue queue;
public Consumer(ITaskQueue queue){
this.queue = queue;
}
public void run(){
while(true){
try {
Thread.sleep((long) (1000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
}
queue.remove();
}
}
}
public class Producer extends Thread{
ITaskQueue queue;
public Producer(ITaskQueue queue){
this.queue = queue;
}
public void run(){
while(true){
try {
Thread.sleep((long) (1000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
}
queue.add();
}
}
~~~
### 使用synchronized wait notify
~~~
public void TaskQueue1 implements ITaskQueue{
//當前資源數量
private int num = 0;
//資源池中允許存放的資源數目
private int size = 10;
public synchronized void add(){
if(num >= size){
wait();
}else{
num ++;
notifyAll();
}
}
public synchronized void remove(){
if(num <= 0){
wait();
}else{
num --;
notifyAll();
}
}
}
~~~
### 使用BlockingQueue
~~~
public void TaskQueue2 implements ITaskQueue{
private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>();
public void add(){
queue.put(1);
}
public void remove(){
queue.talke();
}
}
~~~
## 手寫json解析
### 解法1
[https://github.com/5A59/JsonParser](https://github.com/5A59/JsonParser)
#### Reader
~~~
public class Reader {
private char[] buffer;
private int pos;
public Reader(String json) {
buffer = json.toCharArray();
pos = 0;
}
public char next() throws BufferException{
if (pos < buffer.length){
return buffer[pos];
}
throw new BufferException("no next");
}
public void skipNext() {
pos ++;
}
public void moveToLast() {
pos --;
}
public String nextName() {
//讀取下一個名稱 知道遇到下一個 '"'
return nextString();
}
//讀取下一個value 根據類型的區別 分為 nextBoolean() nextDouble() nextFloat()...
public String nextNumString() {
nextNonWhitespace();
StringBuilder stringBuilder = new StringBuilder();
char c;
while (pos < buffer.length){
c = buffer[pos ++];
if (c == '"' && stringBuilder.length() <= 0){
continue;
}else if (c > '0' && c < '9' || c == '.' || c == '-'){
stringBuilder.append(c);
}else {
pos --;
break;
}
}
return stringBuilder.toString();
}
}
~~~
#### Parser
~~~
public interface Parser {
Object parse(Reader reader);
}
~~~
解析器安裝類型可以分為 ObjectParser , PrimitiveParser(基本類型) , ArrayParser , NullParser
下面以ObjectParser為例
#### ObjectParser
~~~
public class ObjectParser implements Parser {
private static final int START_TAG = -1;
private static final int OBJECT = 0;
private static final int NAME = 1;
private static final int VALUE = 2;
private Stack<Integer> stack;//核心操作棧
private Stack<String> nameStack;//名稱張
private Class<?> raw;
private Map<String, Field> map; // <fieldName, typeName>
private Map<String, Object> map; // <fieldName, typeName>
public ObjectParser(Class<?> raw) {
this.raw = raw;
map = new HashMap<>();
stack = new Stack<>();
nameStack = new Stack<>();
}
public Object parse(Reader reader) {
//一次性class對象解析,存入map
Field[] fields = raw.getDeclaredFields();
for (Field f : fields){
String name = f.getName();
map.put(name, f);
}
Object instance;
try {
instance = raw.newInstance();
} catch (Exception e) {
return null;
}
stack.push(START_TAG);
while (reader.hasNext() && !stack.empty()){
//為了第一次能往下執行初始化
if (stack.peek() == START_TAG){
stack.pop();
}
char c;
try {
c = reader.next();
} catch (Reader.BufferException e) {
e.printStackTrace();
break ;
}
reader.skipNext();
Logger.d("c is " + c);
switch (c){
case '{':
if (stack != null && !stack.isEmpty() && stack.peek() == VALUE){
//如果是value
reader.moveToLast();
setValue(reader, instance);
}else {
//否則就是key
stack.push(OBJECT);
stack.push(NAME);
}
continue;
case '"':
if (stack.peek() == NAME){
//如果是name
String name = reader.nextName();
nameStack.push(name);
stack.pop();
}else if (stack.peek() == VALUE){
//如果是value
setValue(reader, instance);
}
break;
case ',':
stack.push(NAME);
break;
case ':':
stack.push(VALUE);
break;
case '}':
if (stack.peek() == OBJECT){
stack.pop();
}
break;
case ' ':
case '\n':
break;
default:
reader.moveToLast();
setNameAndValue(reader, instance);
break;
}
}
return instance;
}
private void setValue(Reader reader, Object instance) {
//根據類型的不同 初始化不同的 使用不同Parser
//通過反射Field的值調用不同的值Par
~~~
核心思想:
維護一個操作指令棧
[自己動手實現一個簡單的JSON解析器](https://www.cnblogs.com/nullllun/p/8358146.html#autoid-1-0-0)
- Java
- Object
- 內部類
- 異常
- 注解
- 反射
- 靜態代理與動態代理
- 泛型
- 繼承
- JVM
- ClassLoader
- String
- 數據結構
- Java集合類
- ArrayList
- LinkedList
- HashSet
- TreeSet
- HashMap
- TreeMap
- HashTable
- 并發集合類
- Collections
- CopyOnWriteArrayList
- ConcurrentHashMap
- Android集合類
- SparseArray
- ArrayMap
- 算法
- 排序
- 常用算法
- LeetCode
- 二叉樹遍歷
- 劍指
- 數據結構、算法和數據操作
- 高質量的代碼
- 解決問題的思路
- 優化時間和空間效率
- 面試中的各項能力
- 算法心得
- 并發
- Thread
- 鎖
- java內存模型
- CAS
- 原子類Atomic
- volatile
- synchronized
- Object.wait-notify
- Lock
- Lock之AQS
- Lock子類
- 鎖小結
- 堵塞隊列
- 生產者消費者模型
- 線程池