定义:Define an interface for creating an object,but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses. (定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类 的实例化延迟到其子类。)
定义:Provide an interface for creating families of related or dependent objects without specifying their concrete classes. (为创建一组相关或相互依赖的对象提供 一个接口,而且无须指定它们的具体类。)
抽象工厂模式通用类图:
抽象工厂模式通用源码类图:
抽象工厂类代码:
public abstract class AbstractCreator {
//创建 A 产品家族
public abstract AbstractProductA createProductA();
//创建 B 产品家族
public abstract AbstractProductB createProductB();
}
使用场景:
一个对象族(或是一组没有任何关系的对象)都有相同的约束。
涉及不同操作系统的时候,都可以考虑使用抽象工厂模式
4.模板方法模式(TemplateMethodPattern)
定义:Define the skeleton of an algorithm in an operation,deferring some steps to subclasses.Template Method lets subclasses redefine certain steps of an
algorithm without changing the algorithm\’s structure. (定义一个操作中的算法的框 架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义 该算法的某些特定步骤。)
synchronized(obj){
while (条件不满足) {
obj.wait();
}
执行对应逻辑
}
通知
synchronized(obj){
改变条件
obj.notifyAll();
}
ThreadLocal
主要解决每一个线程想绑定自己的值,存放线程的私有数据。
ThreadLocal使用
获取当前的线程的值通过get(),设置set(T) 方式来设置值。
public class XKThreadLocal {
public static ThreadLocal threadLocal = new ThreadLocal();
public static void main(String[] args) {
if (threadLocal.get() == null) {
System.out.println("未设置过值");
threadLocal.set("Java小咖秀 ");
}
System.out.println(threadLocal.get());
}
}
输出:
未设置过值Java小咖秀
Tips:默认值为null
解决get()返回null问题
通过继承重写initialValue()方法即可。
代码实现:
public class ThreadLocalExt extends ThreadLocal {
static ThreadLocalExt threadLocalExt = new ThreadLocalExt();
@Override
protected Object initialValue() {
return "Java小咖秀";
}
public static void main(String[] args) {
System.out.println(threadLocalExt.get());
}
}
public class ThreadLocalExt extends ThreadLocal {
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
} else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
}
public static return new ExecutorService newFixedThreadPool(int nThreads) {
ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //⽤来定位数组索引位置
final K key;
V value;
Node<K,V> next; //链表的下⼀个node
Node(int hash, K key, V value, Node<K,V> next) { … }
public final K getKey(){ … }
public final V getValue() { … }
public final String toString() { … }
public final int hashCode() { … }
public final V setValue(V newValue) { … }
public final boolean equals(Object o) { … }
}
public class Keys {
public static final int MAX_KEY = 10_000_000;
private static final Key[] KEYS_CACHE = new Key[MAX_KEY];
static {
for (int i = 0; i < MAX_KEY; ++i) {
KEYS_CACHE[i] = new Key(i);
}
}
public static Key of(int value) {
return KEYS_CACHE[value];
}
}
理解:子类与父类的关系并不是日常生活中的父子关系,子类与父类而是一种特殊化与一般化的关 系,是is-a的关系,子类是父类更加详细的分类。如class dog extends animal,就可以理解为dog is a animal.注意设计继承的时候,若要让某个类能继承,父类需适当开放访问权限,遵循里氏代换原则,即向修改关闭对扩展开放,也就是开- 闭原则。
逻辑与: a == b & b ==c (即使a==b已经是 false了,程序还会继续判断b是否等于c)
2.&&: 短路与
a== b && b== c (当a==b 为false则不会继续判断b是否等与c)
比如判断某对象中的属性是否等于某值,则必须用&&,否则会出现空指针问题。
IntegerCache是什么?
public class IntegerTest {
public static void main(String[] args) {
Integer a = 100, b = 100 ,c = 129,d = 129;
System.out.println(a==b);
System.out.println(c==d);
}
}
结果:
true
false
小朋友,你是否有很多问号?
来解释一下:
/*Cache to support the object identity semantics of autoboxing for
values between
*-128and 127(inclusive)as required by JLS.
*
*The cache is initialized on first usage.The size of the cache
*may be controlled by the{@code -XX:AutoBoxCacheMax=<size>}option.
*During VM initialization,java.lang.Integer.IntegerCache.high property
*may be set and saved in the private system properties in the
*sun.misc.VM class.
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) - 1);
} catch (NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for (int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {
}
}
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high){
return IntegerCache.cache[i + (-IntegerCache.low)];
}
return new Integer(i);
}