21xrx.com
2024-11-22 15:40:32 Friday
登录
文章检索 我的文章 写文章
掌握JAVA设计模式:精通答案与实际案例分享
2023-06-15 15:23:24 深夜i     --     --
Java设计模式 案例分享 实际答案

Java设计模式是软件开发中非常重要的一部分,掌握设计模式有助于提高软件开发效率和质量。但是掌握设计模式需要理解其实际运用场景和答案,接下来将分享一些实际案例和答案。

单例模式案例:


public class Singleton {

  private static Singleton instance = null;

  private Singleton() {}

  public static Singleton getInstance() {

    if (instance == null) {

      instance = new Singleton();

    }

    return instance;

  }

}

工厂模式案例:


public interface Animal {

  void eat();

}

public class Dog implements Animal {

  @Override

  public void eat() {

    System.out.println("Dog is eating.");

  }

}

public class Cat implements Animal {

  @Override

  public void eat() {

    System.out.println("Cat is eating.");

  }

}

public class AnimalFactory {

  public Animal createAnimal(String animalType) {

    if (animalType.equals("Dog")) {

      return new Dog();

    } else if (animalType.equals("Cat")) {

      return new Cat();

    } else {

      throw new IllegalArgumentException("Invalid animal type.");

    }

  }

}

策略模式案例:


public interface Discount {

  double apply(double price);

}

public class TwentyPercentOff implements Discount {

  @Override

  public double apply(double price) {

    return price * (1 - 0.2);

  }

}

public class TenPercentOff implements Discount {

  @Override

  public double apply(double price) {

    return price * (1 - 0.1);

  }

}

public class Context {

  private Discount discount;

  public Context(Discount discount)

    this.discount = discount;

  

  public double executeDiscount(double price) {

    return discount.apply(price);

  }

}

以上案例仅作为Java设计模式学习的基础内容,更多实际的运用场景和答案需要由具体情况决定。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复