java实现工厂模式、单例模式、策略模式、建造者模式多个设计模式的组合示例
时间: 2023-07-10 11:30:10 浏览: 102
下面是一个 Java 实现工厂模式、单例模式、策略模式、建造者模式多个设计模式的组合示例:
1. 工厂模式(Factory Pattern)
```java
public interface Animal {
void eat();
}
public class Cat implements Animal {
@Override
public void eat() {
System.out.println("Cat is eating!");
}
}
public class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog is eating!");
}
}
public class AnimalFactory {
public static Animal createAnimal(String type) {
if ("cat".equalsIgnoreCase(type)) {
return new Cat();
} else if ("dog".equalsIgnoreCase(type)) {
return new Dog();
} else {
throw new IllegalArgumentException("Invalid animal type: " + type);
}
}
}
```
2. 单例模式(Singleton Pattern)
```java
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
public void showMessage() {
System.out.println("Hello, Singleton!");
}
}
```
3. 策略模式(Strategy Pattern)
```java
public interface DiscountStrategy {
double getDiscount(double originalPrice);
}
public class FixedDiscountStrategy implements DiscountStrategy {
private double discount;
public FixedDiscountStrategy(double discount) {
this.discount = discount;
}
@Override
public double getDiscount(double originalPrice) {
return originalPrice - discount;
}
}
public class PercentageDiscountStrategy implements DiscountStrategy {
private double percentage;
public PercentageDiscountStrategy(double percentage) {
this.percentage = percentage;
}
@Override
public double getDiscount(double originalPrice) {
return originalPrice * (1 - percentage);
}
}
public class ShoppingCart {
private List<Double> items;
private DiscountStrategy strategy;
public ShoppingCart(DiscountStrategy strategy) {
this.strategy = strategy;
this.items = new ArrayList<>();
}
public void addItem(double price) {
items.add(price);
}
public double calculateTotal() {
double sum = 0;
for (Double price : items) {
sum += price;
}
return strategy.getDiscount(sum);
}
}
```
4. 建造者模式(Builder Pattern)
```java
public class User {
private String firstName;
private String lastName;
private int age;
private String email;
private User(Builder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.email = builder.email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "User{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
", email='" + email + '\'' +
'}';
}
public static class Builder {
private String firstName;
private String lastName;
private int age;
private String email;
public Builder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder email(String email) {
this.email = email;
return this;
}
public User build() {
return new User(this);
}
}
}
```
以上是四种设计模式的示例,我们可以将它们组合起来使用,例如:
```java
public class Application {
public static void main(String[] args) {
// 工厂模式
Animal cat = AnimalFactory.createAnimal("cat");
Animal dog = AnimalFactory.createAnimal("dog");
cat.eat();
dog.eat();
// 单例模式
Singleton singleton = Singleton.getInstance();
singleton.showMessage();
// 策略模式
DiscountStrategy fixedDiscount = new FixedDiscountStrategy(10);
DiscountStrategy percentageDiscount = new PercentageDiscountStrategy(0.2);
ShoppingCart cart = new ShoppingCart(percentageDiscount);
cart.addItem(100);
cart.addItem(200);
System.out.println("Total price after discount: " + cart.calculateTotal());
// 建造者模式
User user = new User.Builder("John", "Doe")
.age(30)
.email("john.doe@example.com")
.build();
System.out.println(user);
}
}
```
通过组合多种设计模式,我们可以更好地解决复杂的问题,提高代码的可维护性和可扩展性。
阅读全文