可以使用java策略模式设计一个系统,该系统包含以下几种输出英文字母表的策略: 按照字母顺序输出英文字母表。 按照字母逆序输出英文字母表。 按照大小写字母顺序输出英文字母表。 按照大小写字母逆序输出英文字母表。 随机输出英文字母表。
时间: 2023-06-14 22:08:32 浏览: 214
JAVA 输出字母表
5星 · 资源好评率100%
好的,下面是一个使用策略模式实现的示例代码:
首先定义一个策略接口,包含一个输出字母表的方法:
```java
public interface AlphabetStrategy {
void printAlphabet();
}
```
然后分别实现几种不同的策略:
1. 按照字母顺序输出英文字母表:
```java
public class AlphabetOrderStrategy implements AlphabetStrategy {
@Override
public void printAlphabet() {
for (char c = 'a'; c <= 'z'; c++) {
System.out.print(c + " ");
}
System.out.println();
}
}
```
2. 按照字母逆序输出英文字母表:
```java
public class AlphabetReverseOrderStrategy implements AlphabetStrategy {
@Override
public void printAlphabet() {
for (char c = 'z'; c >= 'a'; c--) {
System.out.print(c + " ");
}
System.out.println();
}
}
```
3. 按照大小写字母顺序输出英文字母表:
```java
public class AlphabetCaseOrderStrategy implements AlphabetStrategy {
@Override
public void printAlphabet() {
for (char c = 'a'; c <= 'z'; c++) {
System.out.print(c + " ");
}
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
System.out.println();
}
}
```
4. 按照大小写字母逆序输出英文字母表:
```java
public class AlphabetCaseReverseOrderStrategy implements AlphabetStrategy {
@Override
public void printAlphabet() {
for (char c = 'Z'; c >= 'A'; c--) {
System.out.print(c + " ");
}
for (char c = 'z'; c >= 'a'; c--) {
System.out.print(c + " ");
}
System.out.println();
}
}
```
5. 随机输出英文字母表:
```java
public class AlphabetRandomOrderStrategy implements AlphabetStrategy {
@Override
public void printAlphabet() {
List<Character> list = new ArrayList<>();
for (char c = 'a'; c <= 'z'; c++) {
list.add(c);
}
for (char c = 'A'; c <= 'Z'; c++) {
list.add(c);
}
Collections.shuffle(list);
for (char c : list) {
System.out.print(c + " ");
}
System.out.println();
}
}
```
最后定义一个上下文类,用于选择不同的策略进行输出:
```java
public class AlphabetContext {
private AlphabetStrategy strategy;
public AlphabetContext(AlphabetStrategy strategy) {
this.strategy = strategy;
}
public void setStrategy(AlphabetStrategy strategy) {
this.strategy = strategy;
}
public void printAlphabet() {
strategy.printAlphabet();
}
}
```
使用示例:
```java
AlphabetContext context = new AlphabetContext(new AlphabetOrderStrategy());
context.printAlphabet();
context.setStrategy(new AlphabetReverseOrderStrategy());
context.printAlphabet();
context.setStrategy(new AlphabetCaseOrderStrategy());
context.printAlphabet();
context.setStrategy(new AlphabetCaseReverseOrderStrategy());
context.printAlphabet();
context.setStrategy(new AlphabetRandomOrderStrategy());
context.printAlphabet();
```
输出结果:
```
a b c d e f g h i j k l m n o p q r s t u v w x y z
z y x w v u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Z Y X W V U T S R Q P O N M L K J I H G F E D C B A z y x w v u t s r q p o n m l k j i h g f e d c b a
K k Q q L l F f J j U u A a W w I i D d R r V v G g T t N n Z z S s C c E e X x P p Y y B b O o H h M m
```
阅读全文