由于只有狗可以玩"获取",这个例子是好还是坏?由于使用了instanceof,我怀疑这是一个非常糟糕的主意,但我不完全确定原因.
class Animal {
var $name;
function __construct($name) {
$this->name = $name;
}
}
class Dog extends Animal {
function speak() {
return "Woof, woof!";
}
function playFetch() {
return 'getting the stick';
}
}
class Cat extends Animal {
function speak() {
return "Meow...";
}
}
$animals = array(new Dog('Skip'), new Cat('Snowball'));
foreach($animals as $animal) {
print $animal->name . " says: " . $animal->speak() . '<br>';
if ($animal instanceof Dog) echo $animal->playFetch();
}
Run Code Online (Sandbox Code Playgroud)
另一个例子.由于我不断创建具有ID的数据对象,我想我也可以从基类扩展它们以避免代码重复.再次,这是不对的?由于椅子没有名字,狗没有轮子.但它们都是数据对象,因此非常令人困惑.
class Data_Object { …Run Code Online (Sandbox Code Playgroud) Alrite,我会直接跳到代码:
public interface Visitor {
public void visitInventory();
public void visitMaxCount();
public void visitCountry();
public void visitSomethingElse();
public void complete();
//the idea of this visitor is that when a validator would visit it, it would validate data
//when a persister visits it, it would persist data, etc, etc.
// not sure if I making sense here...
}
public interface Visitable {
public void accept(Visitor visitor);
}
Run Code Online (Sandbox Code Playgroud)
这是一个基础实现:
public class StoreValidator implements Visitor {
private List <ValidationError> storeValidationErrors = new ArrayList<ValidationError>(); …Run Code Online (Sandbox Code Playgroud) 以下是使用泛型的访问者模式的java实现,一般是否有用?(我想是的).
它能以某种方式得到改善吗?使用匿名类轻松调用很重要.谢谢.
(使用示例):
Vector<Number> numbers = new Vector<Number>();
numbers.add(new Double(1.2));
numbers.add(new Float(-1.2));
numbers.add(new Double(4.8));
numbers.add(new Float(-3.4));
numbers.add(new Long(123456));
numbers.add(new Short("14"));
For.each(numbers, new Visitor<Number>() {
public void doIt(Double n) {
System.out.println("doIt() for double: " + n);
}
public void doIt(Float n) {
System.out.println("doIt() for float: " + n);
}
public void doIt(Number n) {
System.out.println("doIt() for Number: " + n);
}
});
Visitor<Number> visi = new Visitor<Number>() {
private StringBuffer all = new StringBuffer ();
public void doIt(Number n) {
System.out.println("doIt() …Run Code Online (Sandbox Code Playgroud)