参考答案
JDK 常用的设计模式:
1.工厂模式
java.text.DateFormat 工具类,它用于格式化一个本地日期或者时间。
- public final static DateFormat getDateInstance();
- public final static DateFormat getDateInstance(int style);
- public final static DateFormat getDateInstance(int style,Locale locale);
加密类:
- KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
- Cipher cipher = Cipher.getInstance("DESede");
2. 适配器模式
把其他类适配为集合类
- List<Integer> arrayList = java.util.Arrays.asList(new Integer[]{1,2,3});
- List<Integer> arrayList = java.util.Arrays.asList(1,2,3);
3. 代理模式
如 JDK 本身的动态代理。
- interface Animal {
- void eat();
- }
- class Dog implements Animal {
- @Override
- public void eat() {
- System.out.println("The dog is eating");
- }
- }
- class Cat implements Animal {
- @Override
- public void eat() {
- System.out.println("The cat is eating");
- }
- }
- // JDK 代理类
- class AnimalProxy implements InvocationHandler {
- private Object target; // 代理对象
- public Object getInstance(Object target) {
- this.target = target;
- // 取得代理对象
- return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- System.out.println("调用前");
- Object result = method.invoke(target, args); // 方法调用
- System.out.println("调用后");
- return result;
- }
- }
- public static void main(String[] args) {
- // JDK 动态代理调用
- AnimalProxy proxy = new AnimalProxy();
- Animal dogProxy = (Animal) proxy.getInstance(new Dog());
- dogProxy.eat();
- }
4. 单例模式
全局只允许有一个实例,比如:
- Runtime.getRuntime();
5. 装饰器
为一个对象动态的加上一系列的动作,而不需要因为这些动作的不同而产生大量的继承类。
- java.io.BufferedInputStream(InputStream);
- java.io.DataInputStream(InputStream);
- java.io.BufferedOutputStream(OutputStream);
- java.util.zip.ZipOutputStream(OutputStream);
- java.util.Collections.checkedList(List list, Class type) ;
6.模板方法模式
定义一个操作中算法的骨架,将一些步骤的执行延迟到其子类中。
比如,Arrays.sort() 方法,它要求对象实现 Comparable 接口。
- class Person implements Comparable{
- private Integer age;
- public Person(Integer age){
- this.age = age;
- }
- @Override
- public int compareTo(Object o) {
- Person person = (Person)o;
- return this.age.compareTo(person.age);
- }
- }
- public class SortTest(){
- public static void main(String[] args){
- Person p1 = new Person(10);
- Person p2 = new Person(5);
- Person p3 = new Person(15);
- Person[] persons = {p1,p2,p3};
- //排序
- Arrays.sort(persons);
- }
- }
以上,是Java面试题【JDK 类库常用的设计模式有哪些】的参考答案。
输出,是最好的学习方法。
欢迎在评论区留下你的问题、笔记或知识点补充~
—end—