手写单例模式
public class Singleton {
//注意private,static
private static volatile Singleton instance;
//注意private
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
#手写策略模式
1 2 3
| interface PayStrategy { void pay(int amount); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class AliPay implements PayStrategy { @Override public void pay(int amount) { System.out.println("使用支付宝支付:" + amount); } }
class WeChatPay implements PayStrategy { @Override public void pay(int amount) { System.out.println("使用微信支付:" + amount); } }
class CreditCardPay implements PayStrategy { @Override public void pay(int amount) { System.out.println("使用信用卡支付:" + amount); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import java.util.HashMap; import java.util.Map;
class StrategyFactory {
private static final Map<String, PayStrategy> strategies = new HashMap<>(); static { strategies.put("ALI", new AliPay()); strategies.put("WX", new WeChatPay()); strategies.put("CARD", new CreditCardPay()); }
public static PayStrategy getStrategy(String type) { return strategies.get(type); } }
|
1 2
| PayStrategy strategy = StrategyFactory.getStrategy("ALI") strategy.pay(100)
|
手写线程池
import java.util.*;
import java.util.concurrent.*;
public class SimpleThreadPool {
// 任务队列
private BlockingQueue<Runnable> taskQueue;
// 工作线程
private List<Worker> workers = new ArrayList<>();
public SimpleThreadPool(int poolSize, int queueSize) {
taskQueue = new ArrayBlockingQueue<>(queueSize);
for (int i = 0; i < poolSize; i++) {
Worker worker = new Worker();
workers.add(worker);
worker.start();
}
}
// ================<mark> 提交无返回值任务 </mark>================
public void execute(Runnable task) {
try {
taskQueue.put(task);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// ================<mark> 提交有返回值任务 </mark>================
public <T> Future<T> submit(Callable<T> task) {
FutureTask<T> futureTask = new FutureTask<>(task);
try {
taskQueue.put(futureTask);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return futureTask;
}
// ================<mark> Worker </mark>================
private class Worker extends Thread {
@Override
public void run() {
while (true) {
try {
Runnable task = taskQueue.take();
task.run();
} catch (InterruptedException e) {
break;
}
}
}
}
}
手写观察者模式
1 2 3
| interface Observer { void onEvent(Object data); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import java.util.*;
class EventBus {
private final Map<String, List<Observer>> normalMap = new HashMap<>();
private final Map<String, List<Observer>> onceMap = new HashMap<>();
public void subscribe(String eventType, Observer observer) { normalMap .computeIfAbsent(eventType, k -> new ArrayList<>()) .add(observer); }
public void subscribeOnce(String eventType, Observer observer) { onceMap .computeIfAbsent(eventType, k -> new ArrayList<>()) .add(observer); }
public void unsubscribe(String eventType, Observer observer) { List<Observer> list1 = normalMap.get(eventType); if (list1 != null) { list1.remove(observer); }
List<Observer> list2 = onceMap.get(eventType); if (list2 != null) { list2.remove(observer); } }
public void publish(String eventType, Object data) {
List<Observer> normalList = normalMap.get(eventType); if (normalList != null) { for (Observer o : normalList) { o.onEvent(data); } }
List<Observer> onceList = onceMap.get(eventType); if (onceList != null) { for (Observer o : onceList) { o.onEvent(data); } onceMap.remove(eventType); } } }
|
#手写HashMap
import java.util.Objects;
public class MyHashMap<K, V> {
static class Node<K, V> {
K key;
V value;
Node<K, V> next;
Node(K k, V v) {
key = k;
value = v;
}
}
private Node<K, V>[] table = new Node[16];
private int size;
private static final float LOAD_FACTOR = 0.75f;
// hash
private int hash(K key) {
return key == null ? 0 : key.hashCode();
}
// put
public void put(K key, V value) {
int idx = (table.length - 1) & hash(key);
Node<K, V> cur = table[idx];
while (cur != null) {
if (Objects.equals(cur.key, key)) {
cur.value = value; // 覆盖
return;
}
cur = cur.next;
}
Node<K, V> newNode = new Node<>(key, value);
newNode.next = table[idx];
table[idx] = newNode;
size++;
if (size > table.length * LOAD_FACTOR) {
resize();
}
}
// get
public V get(K key) {
int idx = (table.length - 1) & hash(key);
Node<K, V> cur = table[idx];
while (cur != null) {
if (Objects.equals(cur.key, key)) {
return cur.value;
}
cur = cur.next;
}
return null;
}
// resize
private void resize() {
Node<K, V>[] old = table;
table = new Node[old.length * 2];
size = 0;
for (Node<K, V> head : old) {
while (head != null) {
put(head.key, head.value);
head = head.next;
}
}
}
}
}