-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
1607064106-续溢男 #14
Comments
在java8以后为什么还有抽象类:一、 2、设计模式之简单工厂模式什么是简单工厂模式:用一个工厂去创建继承了同一个类(或者实现了同一个接口)的类的实例。实质是根据传入到工厂的参数的不同创建不同的实例。 代码实现:产品抽象接口: public interface Human {
void ishuman();
} 具体的产品类: public class Women implements Human{
@Override
public void ishuman() {
System.out.println("是女人");
}
}
public class Men implements Human {
@Override
public void ishuman() {
System.out.println("是男人");
}
} 简单工厂类: public class SimpleFactory {
private Human people=null;
//利用条件语句判断创建哪个对象的实例
public Human creat(String type)
{
if(type.equals("women"))
{
people=new Women();
}
else if (type.equals("men"))
{
people=new Men();
}
else{
System.out.println("不能创建");
}
return people;
}
} 客户端 import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String s;
System.out.println("你想创建哪个类的实例");
s=input.next();
SimpleFactory simpleFactory=new SimpleFactory();
Human people=simpleFactory.creat(s);
if(people!=null) {
people.ishuman();
}
}
} 运行结果:1.你想要创建哪个类的实例 简单工厂模式的优点;
缺点:
|
第三次作业:创建一个序列 List<String> list=new ArrayList<>();
Scanner input=new Scanner(System.in);
int num,i;
String s;
System.out.println("输入数据的个数");
num=input.nextInt();
for(i=0;i<num;i++)
{
System.out.println("输入第"+(i+1)+"个字符串");
s=input.next();
list.add(s);
} 利用foreach进行遍历(比较推荐的遍历方法) for (String s1:list
) {
System.out.println(s1);
} 利用for语句进行遍历 for (int j = 0; j <list.size(); j++) {
System.out.println(list.get(j));
} 利用迭代器进行遍历Iterator<String >iterator=list.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next());
} 利用stream进行遍历 list.stream().forEach(System.out::println); 运行结果输入: |
The text was updated successfully, but these errors were encountered: