JDK类库常用的设计模式有哪些

参考答案

JDK 常用的设计模式:

1.工厂模式

java.text.DateFormat 工具类,它用于格式化一个本地日期或者时间。

  1. public final static DateFormat getDateInstance();
  2. public final static DateFormat getDateInstance(int style);
  3. public final static DateFormat getDateInstance(int style,Locale locale);

加密类:

  1. KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
  2. Cipher cipher = Cipher.getInstance("DESede");

2. 适配器模式

把其他类适配为集合类

  1. List<Integer> arrayList = java.util.Arrays.asList(new Integer[]{1,2,3});
  2. List<Integer> arrayList = java.util.Arrays.asList(1,2,3);

3. 代理模式

如 JDK 本身的动态代理。

  1. interface Animal {
  2. void eat();
  3. }
  4. class Dog implements Animal {
  5. @Override
  6. public void eat() {
  7. System.out.println("The dog is eating");
  8. }
  9. }
  10. class Cat implements Animal {
  11. @Override
  12. public void eat() {
  13. System.out.println("The cat is eating");
  14. }
  15. }
  16.  
  17. // JDK 代理类
  18. class AnimalProxy implements InvocationHandler {
  19. private Object target; // 代理对象
  20. public Object getInstance(Object target) {
  21. this.target = target;
  22. // 取得代理对象
  23. return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
  24. }
  25. @Override
  26. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  27. System.out.println("调用前");
  28. Object result = method.invoke(target, args); // 方法调用
  29. System.out.println("调用后");
  30. return result;
  31. }
  32. }
  33.  
  34. public static void main(String[] args) {
  35. // JDK 动态代理调用
  36. AnimalProxy proxy = new AnimalProxy();
  37. Animal dogProxy = (Animal) proxy.getInstance(new Dog());
  38. dogProxy.eat();
  39. }

4. 单例模式

全局只允许有一个实例,比如:

  1. Runtime.getRuntime();

5. 装饰器

为一个对象动态的加上一系列的动作,而不需要因为这些动作的不同而产生大量的继承类。

  1. java.io.BufferedInputStream(InputStream);
  2. java.io.DataInputStream(InputStream);
  3. java.io.BufferedOutputStream(OutputStream);
  4. java.util.zip.ZipOutputStream(OutputStream);
  5. java.util.Collections.checkedList(List list, Class type) ;

6.模板方法模式

定义一个操作中算法的骨架,将一些步骤的执行延迟到其子类中。

比如,Arrays.sort() 方法,它要求对象实现 Comparable 接口。

  1. class Person implements Comparable{
  2. private Integer age;
  3. public Person(Integer age){
  4. this.age = age;
  5. }
  6. @Override
  7. public int compareTo(Object o) {
  8. Person person = (Person)o;
  9. return this.age.compareTo(person.age);
  10. }
  11. }
  12. public class SortTest(){
  13. public static void main(String[] args){
  14. Person p1 = new Person(10);
  15. Person p2 = new Person(5);
  16. Person p3 = new Person(15);
  17. Person[] persons = {p1,p2,p3};
  18. //排序
  19. Arrays.sort(persons);
  20. }
  21. }

 

以上,是Java面试题【JDK 类库常用的设计模式有哪些】的参考答案。

输出,是最好的学习方法

欢迎在评论区留下你的问题、笔记或知识点补充~

—end—

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧