我指的是有效Java第2章中讨论的"服务提供者框架" ,这似乎是处理我遇到的问题的正确方法,我需要在运行时实例化几个类中的一个,基于a String选择哪个服务和Configuration对象(本质上是一个XML片段):
但是,我如何让各个服务提供商(例如一堆默认提供商+一些自定义提供商)进行自我注册?
interface FooAlgorithm
{
/* methods particular to this class of algorithms */
}
interface FooAlgorithmProvider
{
public FooAlgorithm getAlgorithm(Configuration c);
}
class FooAlgorithmRegistry
{
private FooAlgorithmRegistry() {}
static private final Map<String, FooAlgorithmProvider> directory =
new HashMap<String, FooAlgorithmProvider>();
static public FooAlgorithmProvider getProvider(String name)
{
return directory.get(serviceName);
}
static public boolean registerProvider(String name,
FooAlgorithmProvider provider)
{
if (directory.containsKey(name))
return false;
directory.put(name, provider);
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
例如,如果我编写自定义类MyFooAlgorithm和MyFooAlgorithmProvider来实现FooAlgorithm,并将它分发到jar中,是否有任何方法可以自动调用registerProvider,或者我使用该算法的客户端程序是否必须显式调用FooAlgorithmRegistry.registerProvider( )他们想要使用的每个班级?
我似乎无法掌握工厂的正确概念.
谁能帮我编码一个简单的测试?我通过互联网阅读了一些文本,并且无法用同样的方式编写代码.其实我无法理解这个过程.复制代码很简单,但我需要了解为什么这不起作用.
class Factory:
def __init__(self):
self.msg = "teste"
def fabricateAnotherObject(self,obj,**kwargs):
return apply(obj,**kwargs)
class testClass:
def __init__(self,nome,salario,endereco):
self.nome = nome
self.salario = salario
self.endereco = endereco
def __str__(self):
return "Nome: " + str(self.nome) + "\nEndereco: " + str(self.endereco) + "\nSalario: " + str(self.salario)
a = Factory()
emp = a.fabricateAnotherObject(testClass,"George",2000,"Three Four Five Avenue")
print str(emp)
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Twisted框架编写一个简单的程序,我正在努力解决(甚至成像如何编写它)问题我找不到任何相关的文档:
主反应堆使用两个工厂,一个自定义,在给定端口(例如,8000)上侦听TCP连接,第二个,以登录到给定的IRC服务器和通道.在工厂收听8000时接收数据(简单,一行文本)时,我需要将该数据传递给第二工厂,然后可以相应地处理它 - 将带有该文本的消息发送到通道,或者发送一条私有消息对某些人而言,现在并不重要.我找不到任何方法从第一个工厂获取数据并将其发送到另一个工厂进行处理(可能像第二个IRC工厂通常收到的连接?).
如果这可以以某种方式解决,那么我想添加一个甚至更多的工厂(例如Jabber)将端口8000上的接收数据一次性发送到所有这些工厂,将其相应地传递给协议(IRC到一个频道, Jabber给一个联系人,等等).
是否有人遇到类似的问题,并愿意给我一些建议,甚至分享一些代码行?任何帮助将非常感谢!
提前致谢.
我有一个单独的Spring bean(并且它必须保持单个),每次执行某个方法时,它需要另一个bean的新实例(让它称之为X).
到目前为止,我看了以下方法:
只需使用new创建X. 这工作了一段时间,但现在我们需要X的Spring AOP功能,所以这不再起作用了,因为生成的实例不是Spring管理的.
我认为FactoryBean是一个依赖项,但我只从FactoryBean获得一个X实例,它不符合我的第一个实例.
当前的计划是在Spring上下文中手动查找X,并在那里使用原型依赖项声明它.这应该有效,但我认为这真的很难看.
=>如何在我的bean中注入一个工厂,以便我可以在任何时候调用它的工厂方法,并从中获取一个spring托管实例.
从JSP文件中删除switch的正确方法是什么?我有一个工厂,可以返回多种类型的对象.每个都有自己的表示逻辑,所以我需要这样的东西:
//From controller
@RequestMapping(value = "/source", method = RequestMethod.POST)
public ModelAndView doMainJob(@RequestParam("text") String text) {
ResultState state = new ResultStateFactory().fromString(text);
ModelAndView model = new ModelAndView("result/view");
model.addObject("state", state);
model.addObject("stateType", state.getClass());
return model;
}
//from jsp/result/view.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="main" tagdir="/WEB-INF/tags" %>
<%@taglib prefix="r" tagdir="/WEB-INF/tags/result" %>
<main:basic_layout>
<jsp:body>
<c:choose>
<c:when test="${stateType == StateA}"><r:stateA param=${state} /></c:when>
<c:when test="${stateType == StateB}"><r:stateB param=${state} /></c:when>
<c:when test="${stateType == StateC}"><r:stateC param=${state} /></c:when>
.
.
.
<c:when test="${stateType == StateX}"><r:stateX param=${state} /></c:when>
<c:when test="${stateType == StateY}"><r:stateY param=${state} …Run Code Online (Sandbox Code Playgroud) .factory('Api', function($http) {
var API = "http://127.0.0.1:4567/";
return {
get: function(method) {
return $http.get(API + method).success(function(result) {
return result;
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后
console.log(Api.get("MAppData"));
Run Code Online (Sandbox Code Playgroud)
返回
Object {then: function, success: function, error: function}
Run Code Online (Sandbox Code Playgroud)
为什么不返回结果(响应数据)?
我一直在用Dart编写一些代码。我真的很喜欢工厂构造函数,但恐怕我在滥用它的用处。特别是在编写值对象类时,如果验证失败,有时会返回null。
class EmailAddress {
static final RegExp _regex = new RegExp(...);
final String _value;
factory EmailAddress(String input) {
return _regex.hasMatch(input) ? new EmailAddress._internal(input) : null;
}
const EmailAddress._internal(this._value);
toString() => _value;
}
Run Code Online (Sandbox Code Playgroud)
一开始,这似乎还不错。但是,当您实际使用它时,这就是您所看到的。
methodThatCreatesAnEmailAddress() {
var emailAddress = new EmailAddress("definitely not an email address");
...
}
Run Code Online (Sandbox Code Playgroud)
为什么这样不好的论点是,来自另一种静态类型的语言(例如Java或C ++)的开发人员会期望emailAddress始终被初始化为非null值。为什么这是完全可以接受的参数是构造函数是工厂,因此可以返回null值。
那么,这是不好的做法还是利用了有用的功能?
我一直在读" Head First:Design Patterns "这本书,我发现它是对设计模式的一个很好的介绍.但是,我对他们在第4章中提出的声明提出了一个问题:
它们定义了"Simple Factory"模式如下(Java伪代码):
public abstract class Product
{
// Product characteristics
// Concrete Products should subclass this
}
public class SimpleFactory {
public Product createProduct(){
// Return an instance of some subclass of Product
}
}
public class Store {
SimpleFactory factory;
public Product orderProduct(){
Product product = factory.createProduct();
// Do some manipulation on product
return product;
}
}
Run Code Online (Sandbox Code Playgroud)
"工厂方法"定义如下(类Product保持不变并省略):
public abstract class Store {
//Concrete Stores must subclass this and override createProduct()
public abstract Product …Run Code Online (Sandbox Code Playgroud) 我有两个独立的实体:
public enum Rule implements Validatable, StringRepresentable{
//...
}
Run Code Online (Sandbox Code Playgroud)
和
public inteface Filter extends Validatable, StringRepresentable{
//...
}
Run Code Online (Sandbox Code Playgroud)
哪里
public inteface Validatable{
public GenericValidator getValidator();
}
Run Code Online (Sandbox Code Playgroud)
和
public interface StringRepresentable{
public String getStringRepresentation();
}
Run Code Online (Sandbox Code Playgroud)
GenericValidator是一个抽象类,有许多我不希望用户直接访问的子类.我该如何更好地处理这些事情?
我不明白何时创建类似的更好
public class ValidatorFactory{
public Validator getRuleValidator(Rule r){ ... }
public Validator getFilterValidator(Filter f){ ... }
}
Run Code Online (Sandbox Code Playgroud)
而不是Validatable如前所示实现接口.
难道没有人解释我怎样才能做出正确的决定?什么潜在的情况需要执行FactoryMethod一个错误的决定,什么时候真的很好?
UPD:
public interface Validator{
public ErrorCode validate();
}
public abstract class GenericValidator implements Validator{
//...
}
Run Code Online (Sandbox Code Playgroud)
本ErrorCode类封装了验证的结果(null如果valiadtion的succsfully完成).
我有以下模拟数据:
interface ISimulationData
{
string Name { get; }
int[] Heights { get; }
int[] Temperatures { get; }
}
Run Code Online (Sandbox Code Playgroud)
以下用于生成的界面:
interface ISimulation
{
void Generate();
}
Run Code Online (Sandbox Code Playgroud)
使用Composite模式表示单个或多个模拟:
interface ISimpleSimulation : ISimulation
{
int Height { get; }
int Temperature { get; }
}
interface IMultiSimulation : ISimulation
{
IEnumerable<ISimulation> GetSimulations();
}
Run Code Online (Sandbox Code Playgroud)
我有以下工厂界面:
interface ISimulationFactory
{
ISimulation CreateSimulation(ISimulationData simulationData);
}
Run Code Online (Sandbox Code Playgroud)
模拟类型的具体实现:
class SimpleSimulation : ISimpleSimulation
{
public int Height { get; set; }
public int Temperature …Run Code Online (Sandbox Code Playgroud)