工厂模式:
看代码一切你就明白了
package
test;
interface
Fruit{
public
void
eat();
}
class
M
implements
Fruit{
public
void
eat() {
System.
out
.println(
"吃 MM"
);
}
}
class
Gg
implements
Fruit{
public
void
eat() {
System.
out
.println(
"吃GG"
);
}
}
class
Factory{
public
static
Fruit getInstance(String userName){
Fruit fruit=
null
;
if
(
"mm"
.equals(userName)){
fruit=
new
M();
}
if
(
"gg"
.equals(userName)){
fruit=
new
Gg();
}
return
fruit;
}
}
public
class
FactoryTest {
public
static
void
main(String[] args) {
Fruit f=
null
;
f=Factory. getInstance(
"mm"
);
f.eat();
}
}
结果:
吃 MM
工厂模式就是像工厂一样的生产东西(对象),你需要什么,就生产什么。