package com.test.proxy; public interface Target { public String execute(); }
package com.test.proxy; public class TargetImpl implements Target { @Override public String execute() { System.out.println("TargetImpl execute!"); return "execute"; } }
package com.test.proxy; public class Proxy implements Target{ private Target target; public Proxy(Target target) { this.target = target; } @Override public String execute() { System.out.println("perProcess"); String result = this.target.execute(); System.out.println("postProcess"); return result; } }
package com.test.proxy; public class ProxyTest { public static void main(String[] args) { Target target = new TargetImpl(); Proxy p = new Proxy(target); String result = p.execute(); System.out.println(result); } }
perProcess TargetImpl execute! postProcess execute
package com.test.dynamic; public interface Target { public String execute(); }
package com.test.dynamic; public class TargetImpl implements Target { @Override public String execute() { System.out.println("TargetImpl execute!"); return "execute"; } }
package com.test.dynamic; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class DynamicProxyHandler implements InvocationHandler{ private Target target; public DynamicProxyHandler(Target target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("========before=========="); Object result = method.invoke(target,args); System.out.println("========after==========="); return result; } }
package com.test.dynamic; import java.lang.reflect.Proxy; public class DynamicProxyTest { public static void main(String[] args) { Target target = new TargetImpl(); DynamicProxyHandler handler = new DynamicProxyHandler(target); Target proxySubject = (Target) Proxy.newProxyInstance(TargetImpl.class.getClassLoader(),TargetImpl.class.getInterfaces(),handler); String result = proxySubject.execute(); System.out.println(result); } }
========before========== TargetImpl execute! ========after=========== execute
package com.test.cglib; public class Target { public String execute() { String message = "-----------test------------"; System.out.println(message); return message; } }
package com.test.cglib; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class MyMethodInterceptor implements MethodInterceptor{ @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println(">>>>MethodInterceptor start..."); Object result = proxy.invokeSuper(obj,args); System.out.println(">>>>MethodInterceptor ending..."); return "result"; } }
package com.test.cglib; import net.sf.cglib.proxy.Enhancer; public class CglibTest { public static void main(String[] args) { System.out.println("***************"); Target target = new Target(); CglibTest test = new CglibTest(); Target proxyTarget = (Target) test.createProxy(Target.class); String res = proxyTarget.execute(); System.out.println(res); } public Object createProxy(Class targetClass) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(targetClass); enhancer.setCallback(new MyMethodInterceptor()); return enhancer.create(); } }
*************** >>>>MethodInterceptor start... -----------test------------ >>>>MethodInterceptor ending... result
public class Singleton2 { private static Singleton2 instance; private Singleton2() {} public static synchronized Singleton2 getInstance() { if (instance == null) { instance = new Singleton2(); } return instance; } }
public class Singleton3 { private static Singleton3 instance = new Singleton3(); private Singleton3() {} public static Singleton3 getInstance() { return instance; } }
public class Singleton7 { private static volatile Singleton7 instance = null; private Singleton7() {} public static Singleton7 getInstance() { if (instance == null) { synchronized (Singleton7.class) { if (instance == null) { instance = new Singleton7(); } } } return instance; } }
public interface Shape { void draw(); }
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } }
public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
public class ShapeFactory { //使用 getShape 方法获取形状类型的对象 public Shape getShape(String shapeType) { if (shapeType == null) { return null; } shapeType = shapeType.toLowerCase(); switch (shapeType) { case "circle": return new Circle(); case "rectangle": return new Rectangle(); case "square": return new Square(); default: return null; } } }
public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //获取 Circle 的对象,并调用它的 draw 方法 Shape shape1 = shapeFactory.getShape("CIRCLE"); //调用 Circle 的 draw 方法 shape1.draw(); //获取 Rectangle 的对象,并调用它的 draw 方法 Shape shape2 = shapeFactory.getShape("RECTANGLE"); //调用 Rectangle 的 draw 方法 shape2.draw(); //获取 Square 的对象,并调用它的 draw 方法 Shape shape3 = shapeFactory.getShape("SQUARE"); //调用 Square 的 draw 方法 shape3.draw(); } }
Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method.
public class Subject { private List<Observer> observers = new ArrayList<>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyAllObservers(); } public void attach(Observer observer) { observers.add(observer); } public void notifyAllObservers() { for (Observer observer : observers) { observer.update(); } } }
public abstract class Observer { protected Subject subject; public abstract void update(); }
public class BinaryObserver extends Observer { public BinaryObserver(Subject subject) { this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println("Binary String: " Integer.toBinaryString(subject.getState())); } }
public class OctalObserver extends Observer { public OctalObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Octal String: " Integer.toOctalString( subject.getState() ) ); } }
public class HexaObserver extends Observer { public HexaObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Hex String: " Integer.toHexString( subject.getState() ).toUpperCase() ); } }
public class ObserverPatternDemo { public static void main(String[] args) { Subject subject = new Subject(); new BinaryObserver(subject); new HexaObserver(subject); new OctalObserver(subject); System.out.println("First state change: 15"); subject.setState(15); System.out.println(); System.out.println("Second state change: 10"); subject.setState(10); } }
First state change: 15 Binary String: 1111 Hex String: F Octal String: 17 Second state change: 10 Binary String: 1010 Hex String: A Octal String: 12
public interface Shape { void draw(); }
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Shape: Rectangle"); } }
public class Circle implements Shape { @Override public void draw() { System.out.println("Shape: Circle"); } }
public abstract class ShapeDecorator implements Shape { protected Shape decoratorShape; public ShapeDecorator(Shape decoratorShape) { this.decoratorShape = decoratorShape; } @Override public void draw() { decoratorShape.draw(); } }
public class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape decoratorShape) { super(decoratorShape); } @Override public void draw() { decoratorShape.draw(); setRedBorder(decoratorShape); } private void setRedBorder(Shape decoratorShape) { System.out.println("Border Color: Red"); } }
public class DecoratorPatternDemo { public static void main(String[] args) { Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); System.out.println("Circle with normal border"); circle.draw(); System.out.println("\nCircle of red border"); redCircle.draw(); System.out.println("\nRectangle of red border"); redRectangle.draw(); } }
Circle with normal border Shape: Circle Circle of red border Shape: Circle Border Color: Red Rectangle of red border Shape: Rectangle Border Color: Red
public static void main(String[] args) { int[] array = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48}; // 只需要修改成对应的方法名就可以了 bubbleSort(array); System.out.println(Arrays.toString(array)); }
/** * Description:冒泡排序 * * @param array 需要排序的数组 * @author JourWon * @date 2019/7/11 9:54 */ public static void bubbleSort(int[] array) { if (array == null || array.length <= 1) { return; } int length = array.length; // 外层循环控制比较轮数i for (int i = 0; i < length; i ) { // 内层循环控制每一轮比较次数,每进行一轮排序都会找出一个较大值 // (array.length - 1)防止索引越界,(array.length - 1 - i)减少比较次数 for (int j = 0; j < length - 1 - i; j ) { // 前面的数大于后面的数就进行交换 if (array[j] > array[j 1]) { int temp = array[j 1]; array[j 1] = array[j]; array[j] = temp; } } } }
public static void main(String[] args) { int[] array = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48}; // 只需要修改成对应的方法名就可以了 selectionSort(array); System.out.println(Arrays.toString(array)); }
/** * Description: 选择排序 * * @param array * @return void * @author JourWon * @date 2019/7/11 23:31 */ public static void selectionSort(int[] array) { if (array == null || array.length <= 1) { return; } int length = array.length; for (int i = 0; i < length - 1; i ) { // 保存最小数的索引 int minIndex = i; for (int j = i 1; j < length; j ) { // 找到最小的数 if (array[j] < array[minIndex]) { minIndex = j; } } // 交换元素位置 if (i != minIndex) { swap(array, minIndex, i); } } } /** * Description: 交换元素位置 * * @param array * @param a * @param b * @return void * @author JourWon * @date 2019/7/11 17:57 */ private static void swap(int[] array, int a, int b) { int temp = array[a]; array[a] = array[b]; array[b] = temp; }
public static void main(String[] args) { int[] array = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48}; // 只需要修改成对应的方法名就可以了 quickSort(array); System.out.println(Arrays.toString(array)); }
/** * Description: 快速排序 * * @param array * @return void * @author JourWon * @date 2019/7/11 23:39 */ public static void quickSort(int[] array) { quickSort(array, 0, array.length - 1); } private static void quickSort(int[] array, int left, int right) { if (array == null || left >= right || array.length <= 1) { return; } int mid = partition(array, left, right); quickSort(array, left, mid); quickSort(array, mid 1, right); } private static int partition(int[] array, int left, int right) { int temp = array[left]; while (right > left) { // 先判断基准数和后面的数依次比较 while (temp <= array[right] && left < right) { --right; } // 当基准数大于了 arr[left],则填坑 if (left < right) { array[left] = array[right]; left; } // 现在是 arr[right] 需要填坑了 while (temp >= array[left] && left < right) { left; } if (left < right) { array[right] = array[left]; --right; } } array[left] = temp; return left; }
public static Integer recursionMulity(Integer n) { if (n == 1) { return 1; } return n * recursionMulity(n - 1); }
public static int fib(int mon) { if (mon < 2) { return 1; } else { return fib(mon - 1) fib(mon - 2); } }
public class BinarySearch { public static void main(String[] args) { int[] arr = {5, 12, 23, 43, 66, 98, 100}; System.out.println(binarySort(arr, 23)); } /** * 循环实现二分查找 * * @param arr * @param key * @return */ public static int binarySearch(int[] arr, int key) { //第一个下标 int low = 0; //最后一个下标 int high = arr.length - 1; int mid = 0; //防越界 if (key < arr[low] || key > arr[high] || low > high) { return -1; } while (low <= high) { mid = (low high) >>> 1; if (key < arr[mid]) { high = mid - 1; } else if (key > arr[mid]) { low = mid 1; } else { return mid; } } return -1; } }
public class ConsistentHash<T> { /** * 节点的复制因子,实际节点个数 * numberOfReplicas = 虚拟节点个数 */ private final int numberOfReplicas; /** * 存储虚拟节点的hash值到真实节点的映射 */ private final SortedMap<Integer, T> circle = new TreeMap<Integer, T>(); public ConsistentHash(int numberOfReplicas, Collection<T> nodes) { this.numberOfReplicas = numberOfReplicas; for (T node : nodes) { add(node); } } public void add(T node) { for (int i = 0; i < numberOfReplicas; i ) { // 对于一个实际机器节点 node, 对应 numberOfReplicas 个虚拟节点 /* * 不同的虚拟节点(i不同)有不同的hash值,但都对应同一个实际机器node * 虚拟node一般是均衡分布在环上的,数据存储在顺时针方向的虚拟node上 */ String nodestr = node.toString() i; int hashcode = nodestr.hashCode(); System.out.println("hashcode:" hashcode); circle.put(hashcode, node); } } public void remove(T node) { for (int i = 0; i < numberOfReplicas; i ) { circle.remove((node.toString() i).hashCode()); } } /** * 获得一个最近的顺时针节点,根据给定的key 取Hash * 然后再取得顺时针方向上最近的一个虚拟节点对应的实际节点 * 再从实际节点中取得 数据 * * @param key * @return */ public T get(Object key) { if (circle.isEmpty()) { return null; } // node 用String来表示,获得node在哈希环中的hashCode int hash = key.hashCode(); System.out.println("hashcode----->:" hash); //数据映射在两台虚拟机器所在环之间,就需要按顺时针方向寻找机器 if (!circle.containsKey(hash)) { SortedMap<Integer, T> tailMap = circle.tailMap(hash); hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); } return circle.get(hash); } public long getSize() { return circle.size(); } /** * 查看表示整个哈希环中各个虚拟节点位置 */ public void testBalance() { //获得TreeMap中所有的Key Set<Integer> sets = circle.keySet(); //将获得的Key集合排序 SortedSet<Integer> sortedSets = new TreeSet<Integer>(sets); for (Integer hashCode : sortedSets) { System.out.println(hashCode); } System.out.println("----each location 's distance are follows: ----"); /* * 查看相邻两个hashCode的差值 */ Iterator<Integer> it = sortedSets.iterator(); Iterator<Integer> it2 = sortedSets.iterator(); if (it2.hasNext()) { it2.next(); } long keyPre, keyAfter; while (it.hasNext() && it2.hasNext()) { keyPre = it.next(); keyAfter = it2.next(); System.out.println(keyAfter - keyPre); } } public static void main(String[] args) { Set<String> nodes = new HashSet<String>(); nodes.add("A"); nodes.add("B"); nodes.add("C"); ConsistentHash<String> consistentHash = new ConsistentHash<String>(2, nodes); consistentHash.add("D"); System.out.println("hash circle size: " consistentHash.getSize()); System.out.println("location of each node are follows: "); consistentHash.testBalance(); String node = consistentHash.get("apple"); System.out.println("node----------->:" node); } }
END 来源:thinkwon.blog.csdn.net/article/details/105870730 十期推荐 【191期】面试官:你能说说SOA架构和微服务架构的区别嘛? 【192期】面试官:线程池中多余的线程是如何回收的? 【193期】如何利用装饰者模式在不改变原有对象的基础上扩展功能 【194期】Redis——第三方jar没有封装的命令我们该怎么执行? 【195期】MySQL中的条件判断函数 CASE WHEN、IF、IFNULL你会用吗? 【196期】夯实基础,Java8新特性Stream详细教程 【197期】华为OD两轮技术面试记录,给后来人一个参考! 【198期】面试官:你能说出 方法重载和方法重写 的原理吗? 【199期】100%会用到的hashCode()和equals()方法及使用规范,你掌握了吗? 【200期】面试官:你能简单说说 SpringMVC 的执行原理吗? ? ~